2

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

2
  • @wOxxOm To clarify, the script inside the XML is working without any extra attributes. The problem is in the injected code. I've added the xmlns to the injected script tag but still not luck Commented Nov 11, 2018 at 11:01
  • @wOxxOm sorry, I missed the createElementNS in your comment. That did the trick! Thank you. If you create an answer from it, I will accept it Commented Nov 11, 2018 at 14:38

1 Answer 1

2

Simply create the script DOM element with an XML-compatible namespace:

let script = document.createElementNS('http://www.w3.org/1999/xhtml', 'script');
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.