I have the following code in my background script:
chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) {
if (changeinfo.status !== 'complete')
return;
if (!matchesUrlFilters(tab.url))
return;
chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
chrome.tabs.executeScript(tabId, { file: "enhance.js" });
});
});
However, this seems to inject my content script twice in some cases (it might happen when enhance.js
does window.history.pushState
).
How can I fInd out whether the tab already has my content script? I tried chrome.tabs.sendRequest
but it never called the callback if the content script was not yet added.
Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.
To use Read Aloud, navigate to the web page you want to read, then click the Read Aloud icon on the Chrome menu. In addition, the shortcut keys ALT-P, ALT-O, ALT-Comma, and ALT-Period can be used to Play/Pause, Stop, Rewind, and Forward. You may also select the text you want to read before activating the extension.
EDIT: Updated per first comment on this answer.
You might try something like this. Add a onRequest listener that will be used as a callback to load the scripts you want, but they will only load based on a value sent as part of the request message. Then use executeScript to call "code" directly that sends a message with the value of a global variable (if it exists).
chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) {
...
// execute a content script that immediately sends back a message
// that checks for the value of a global variable which is set when
// the library has been loaded
chrome.tabs.executeScript(tabId, {
code: "chrome.extension.sendRequest({ loaded: EnhanceLibIsLoaded || false });"
});
...
});
// listen for requests
chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
if (req.loaded === false) {
chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
chrome.tabs.executeScript(tabId, { file: "enhance.js" }, function() {
// set the global variable that the scripts have been loaded
// this could also be set as part of the enhance.js lib
chrome.tabs.executeScript(tabId, { code: "var EnhanceLibIsLoaded = true;" });
});
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With