【问题标题】:window.open, source code viewer and highlight.jswindow.open,源代码查看器和 highlight.js
【发布时间】:2021-07-30 01:35:04
【问题描述】:

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

过程很简单:

  1. 我正在使用 AJAX 获取页面 HTML 及其 URL(这里我使用 jQuery)
  2. 我将结果内容放在一个窗口中并显示出来。
  3. 在窗口中,Highlight.js (应该)对代码进行着色

与本主题类似: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 错误。 问题出在哪里?谢谢你帮助我。

编辑:添加了一个缺失的括号,但效果不大。

【问题讨论】:

  • 你能做一个jsfiddle吗?
  • 只要我知道,highlight.js 需要知道必须突出显示的内容。那么你具体想做什么呢。
  • 因此,正如我在 highlight.js 文档中所读到的那样,您应该使用一个类命名要突出显示的元素,在我的情况下,我想使用 HTML 语法,并且当我们初始化对象时,它应该自动完成......但不是。
  • 无法制作jsfiddle,它说我只输入js内容而不是html...奇怪

标签: javascript jquery html ajax highlight.js


【解决方案1】:

很抱歉,我现在正在尝试这个并且我做到了,但是.. 无论如何,如果有人需要带有可编辑和实时容器的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2011-05-16
    • 2010-12-21
    • 1970-01-01
    • 2011-12-07
    • 2016-01-01
    相关资源
    最近更新 更多