0

I'm actually trying to make a source code viewer for website based on AJAX and popups windows. This will allowing to me to customize the viewer. I'm using hightlight.js for syntaxing, but it's the first time I use that libray.

The process is simple:

  1. I'm getting the page HTML with its URL using AJAX (here I'm using jQuery)
  2. I put the resulted content in a window and show it.
  3. On the window, Highlight.js is (supposed) to get the code colorized

Similar to this topic: Programmatically open "View Source" HTML Window in Browser with Javascript? but with syntax highlighting in addition. Unfortunely the window is shown with the code inside, but that one is not colorized.

This is the entire function (it provides a fallback for cross-origin requests)

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");
        }
    });
}

But I verified my code many times and everything seems fine. Firefox dev tools indicated that CSS and JS file are loaded successfully (GET) and no JS errors. Where is the problem? Thanks to help me.

EDIT: added a missing parenthesis but not working much.

Community
  • 1
  • 1

1 Answers1

0

i am sorry i am trying this now and i did it , but .. anyway if anyone need highlight.js with the container editable and live ,without loosing position of the caret inside the editable part is welcome to use this(and improve it -if possible):

 <!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>