I know xml shouldn't really have javascript in it but I'm making a browser extension that needs to inject some code on every page to provide the user with some interesting statistics.
The problem is, I'm unable to get the injected code to run in XML documents as it looks like the script tag I create is treated as text?
The same code works fine in HTML
Here's what I have:
manifest.json:
"content_scripts": [
{
"matches": ["<all_urls>"],
"all_frames": true,
"match_about_blank": true,
"run_at": "document_start",
"js": ["scripts/content/countCalls.js"]
}
]
countCalls.js:
let injectedCode = 'console.log("Hello from injected code");';
let script = document.createElement('script');
script.appendChild(document.createTextNode(injectedCode));
let parent = document.head || document.body || document.documentElement;
let firstChild = (parent.childNodes && (parent.childNodes.length > 0)) ? parent.childNodes[0] : null;
if (firstChild) {
parent.insertBefore(script, firstChild);
} else {
parent.appendChild(script);
}
test.xml:
<?xml version="1.0"?>
<main xmlns='http://www.w3.org/1999/xhtml'>
<script>
console.log("Hello from XML");
</script>
</main>
When I load test.xml in the browser I see this:
console.log("Hello from injected code");
and in the console I just see this:
Hello from XML
So the injected code is being treated like text. Anyway around this? Otherwise intentionally adding javascript to xml will cause it to bypass the extension
xmlnsto the injected script tag but still not luckcreateElementNSin your comment. That did the trick! Thank you. If you create an answer from it, I will accept it