I’m building a Google Chrome extension. The basic setup is I have a Browser action button that injects jQuery and another bit of JavaScript into the active tab when it is clicked to do it’s thing.
This is my first Chrome extension, but it seems like if the user clicks the button to take action a second time the scripts will be re-injected. This is a problem because the main pages this is going to work with are all AJAX, so the page content changes significantly but the actual page URL never changes.
Is this a legitimate concern, or am I over thinking it and is there a simple way to prevent the scripts from being injected multiple times into the same page? Should I perhaps be specifying these as content scripts instead?
Advertisement
Answer
It is absolutely a legitimate concern.
The easy way would be to use a mechanism similar to #ifndef
include guards in C.
Define a flag that gets set once the content script gets executed, and check if it’s defined before doing anything. All scripts injected from the same extension share the JS execution context and therefore global scope.
Your content script might look like this:
if (window.contentScriptInjected !== true) { window.contentScriptInjected = true; // global scope /* Do your initialization and work */ } /* global function definitions */
The check should use an explicit true
value to avoid false positives on pages that happen to have an element with id
attribute that accidentally equals the variable name – browsers create an implicit global variable that points to that DOM element so for an if
check it’ll be truthy.