简体   繁体   中英

Dynamic Code Snippet Display In Javascript

I am writing a JS function:

showCodeSnippet(fileName)
Input: Local File Name 
Output: Display Code in HTML

I know about the security constraints which restrict accessing local files in browser, but managed to create a workaround solution.

Please consider this Code (working on Firefox 57.0, 64-bit):

<html>
<head>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
</head>

<body>

<script>

async function showCodeSnippet(fileName) 
{        
    const response = await fetch(fileName);
    const text = await response.text(); 

    var parser = new DOMParser();
    var domString = "<pre class=\"prettyprint\">" + text + "</pre>";
    var html = parser.parseFromString(domString, 'text/html');  
    document.body.append(html.body.firstChild);
}
</script>


<script>
showCodeSnippet('Code.txt');
</script>

</body>
</html>

Code.txt contains some sample C++ code:

using namespace std;
int main()
{
     int n;
     cout << "Enter an integer: ";
     cin >> n;

     if ( n % 2 == 0)
            cout << n << " is even.";
     else
            cout << n << " is odd.";
     return 0;
}

Output HTML Page: 在此处输入图片说明

Problem Statement:

Syntax Highlighting is NOT working.

Tried:

  • Google code-prettify
  • Prism Highlighter

These highlighters work fine in case of static code under tags in HTML.

Can someone please provide any hint - root cause of this problem or shall I think in any other direction to achieve this type of functionality ?

Thanks

I see a difference in Chrome. When i Use Firefox, i get the same problem as you. Hold on, i will check some things :)

When you add PR.prettyPrint(); after your appending, the pretty-print will also work in FireFox. seems that the automated repaint is not supported in FireFox by the code :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM