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;
}
Problem Statement:
Syntax Highlighting is NOT working.
Tried:
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 :(