1

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: enter image description here

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

1 Answer 1

1

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 :(

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.