window.open,源代码查看器和highlight.js

时间:2015-12-28 23:38:08

标签: javascript jquery html ajax highlight.js

我实际上是在尝试为基于AJAX和弹出窗口的网站制作源代码查看器。这将允许我自定义查看器。我使用hightlight.js进行语法化,但这是我第一次使用该库。

这个过程很简单:

  1. 我使用AJAX获取带有URL的页面HTML(我在这里使用 jQuery的)
  2. 我将结果内容放在窗口中并显示出来。
  3. 在窗口中,Highlight.js(假设)将代码着色
  4. 与此主题类似:Programmatically open "View Source" HTML Window in Browser with Javascript?但另外还有语法突出显示。不幸的是,窗口显示的是里面的代码,但是那个没有着色。

    这是整个功能(它为跨源请求提供了后备)

    function show_source(link) {
        $.ajax({
            method: "GET",
            url: link,
            dataType: "html",
            success: function (data) {
                var source = data;
                //parse special chars
                source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                // add <pre> tags to preserve whitespace
                source = "<!DOCTYPE html><html><head><link rel='stylesheet' href='/css/include/default.css'><script src='/lib/include/highlight.pack.js'></script><script>hljs.initHighlightingOnLoad(document.getElementById('code'));</script></head><body><pre id='code' class='html'>" + source + "</pre></body></html>";
                //now open the window and set the source as the content
                var sourceWindow = window.open('', 'Source code of ' + link + '', 'height=800,width=800,scrollbars=1,resizable=1');
                if (!sourceWindow || sourceWindow.closed || typeof sourceWindow.closed == 'undefined') {
                    alert("Please allows this popup window to be shown");
                } else {
                     sourceWindow.document.write(source);
                    sourceWindow.document.close(); //close the document for    writing, not the window
                    //give source window focus
                    if (window.focus) {
                        sourceWindow.focus();
                    }
                }
            },
            error: function(){
                window.open("view-source:"+link+"", "_blank");
            }
        });
    }
    

    但我多次验证我的代码,一切似乎都很好。 Firefox开发工具表明CSS和JS文件已成功加载(GET)并且没有JS错误。 问题出在哪儿?谢谢你的帮助。

    编辑:添加了一个缺失的括号,但没有多少工作。

1 个答案:

答案 0 :(得分:0)

对不起,我现在正在尝试这个并且我做到了,但是..无论如何,如果有人需要带有可编辑和实时容器的highlight.js,而不会丢失可编辑部分内插入符号的位置欢迎使用它(并改进它 - 如果可能):

 <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>just time spare</title>
    </head>
    <body>
    
    
    <style>
    .hljs {
        white-space: pre;
        overflow-x: auto;
    }
    </style>
    
    
    <script>
    
        var sw=true; 
    
    </script>
    
    
    <pre>
    <code id="editor" class="editor language-php language-html"  contenteditable="true" onkeyup="if(sw){sw=false;where=getPos(this);dummything();setPos(this,where);}" onkeydown="sw=true;" >
    &lt;?php
        echo 'yep!';
        print('yahoo');
        exit();
    ?&gt;
    &lt;b&gt;sdsadasd&lt;/b&gt;
    
    </code> 
    </pre>  
    
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/highlight.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        hljs.highlightAll();
    
        function dummything(){  
                hljs.highlightAll();
                
        }
    
        /*https://www.cssscript.com/demo/set-get-caret-position/*/
        (function (global, factory) {
          if (typeof define === "function" && define.amd) {
            define('VanillaCaret', ['module'], factory);
          } else if (typeof exports !== "undefined") {
            factory(module);
          } else {
            var mod = {
              exports: {}
            };
            factory(mod);
            global.VanillaCaret = mod.exports;
          }
        })(this, function (module) {
          'use strict';
    
          function _classCallCheck(instance, Constructor) {
            if (!(instance instanceof Constructor)) {
              throw new TypeError("Cannot call a class as a function");
            }
          }
    
          var _createClass = function () {
            function defineProperties(target, props) {
              for (var i = 0; i < props.length; i++) {
                var descriptor = props[i];
                descriptor.enumerable = descriptor.enumerable || false;
                descriptor.configurable = true;
                if ("value" in descriptor) descriptor.writable = true;
                Object.defineProperty(target, descriptor.key, descriptor);
              }
            }
    
            return function (Constructor, protoProps, staticProps) {
              if (protoProps) defineProperties(Constructor.prototype, protoProps);
              if (staticProps) defineProperties(Constructor, staticProps);
              return Constructor;
            };
          }();
    
          var VanillaCaret = function () {
            function VanillaCaret(target) {
              _classCallCheck(this, VanillaCaret);
    
              this.target = target;
              this.isContentEditable = target && target.contentEditable;
            }
    
            _createClass(VanillaCaret, [{
              key: 'getPos',
              value: function getPos() {
                if (document.activeElement !== this.target) {
                  return -1;
                }
                if (this.isContentEditable) {
                  this.target.focus();
                  var _range = document.getSelection().getRangeAt(0);
                  var range = _range.cloneRange();
                  range.selectNodeContents(this.target);
                  range.setEnd(_range.endContainer, _range.endOffset);
                  return range.toString().length;
                }
    
                return this.target.selectionStart;
              }
            }, {
              key: 'setPos',
              value: function setPos(position) {
                if (this.isContentEditable) {
                  if (position >= 0) {
                    var selection = window.getSelection();
                    var range = this.createRange(this.target, {
                      count: position
                    });
                    if (range) {
                      range.collapse(false);
                      selection.removeAllRanges();
                      selection.addRange(range);
                    }
                  }
                } else {
                  this.target.setSelectionRange(position, position);
                }
              }
            }, {
              key: 'createRange',
              value: function createRange(node, chars, range) {
                if (!range) {
                  range = document.createRange();
                  range.selectNode(node);
                  range.setStart(node, 0);
                }
                if (chars.count === 0) {
                  range.setEnd(node, chars.count);
                } else if (node && chars.count > 0) {
                  if (node.nodeType === Node.TEXT_NODE) {
                    if (node.textContent.length < chars.count) {
                      chars.count -= node.textContent.length;
                    } else {
                      range.setEnd(node, chars.count);
                      chars.count = 0;
                    }
                  } else {
                    for (var lp = 0; lp < node.childNodes.length; lp++) {
                      range = this.createRange(node.childNodes[lp], chars, range);
                      if (chars.count === 0) {
                        break;
                      }
                    }
                  }
                }
                return range;
              }
            }]);
    
            return VanillaCaret;
          }();
    
          module.exports = VanillaCaret;
        });
        
    /*fixed code from same source*/
        function setPos(obj,pos) {
              var caret = new VanillaCaret(obj);
              var value = parseInt(pos);
              caret.setPos(value);
        }
    
        function getPos(obj) {
              var caret = new VanillaCaret(obj);
              return caret.getPos();
        }
    </script>
    
    </body>
    </html>