Why do we need to remove script tag after injecting script from chrome extension?

  google-chrome-extension, javascript

Code based on this answer: https://stackoverflow.com/a/9517879/947111

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

After the script has been loaded, the script tag being removed. And indeed if we try to debug target web page, if we will remove this.remove() line, after script was inject there is following line:

enter image description here

In every example where I’ve found injected script is being removed, but my question is why it’s necessary?

What I want to achieve is to check if this script already was injected and if not inject it. If remaining script tag is antipattern, how can I check that script already was injected?

Source: Ask Javascript Questions

LEAVE A COMMENT