Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

javascript - Avoid dynamically injecting the same script multiple times when using chrome.tabs.executeScript(...)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...