I have a content script with a lot of functions in it, i would like to be able to split out those functions into other scripts
Is there any magic needed to call other scripts from the content script
my manifest contains both scripts
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"content.js",
"other.js"
]
}
]
my content script is working fine
however if i put a function in the other.js file and step through it, anything i reference in other.js is undefined
is there anything i should know here?
Edit:
This is just a simple example, the Test function should run on contentscript load
contentscript.js
Test();
other.js;
function Test(){
return true;
}
Google is telling me uncaught ReferenceError, Test not defined
According to the docs on Content Scripts:
js: The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array.
In your case, content.js
would be injected first and try to execute other
's Test()
function, before other.js
is loaded).
Note that based on your manifest, both scripts will be loaded at "document_idle", so even if content.js
has registered the call to Test()
to be run after the page is loaded, it should still run immediately (since the page is already loaded.
If you want your scripts to be injected before the page's content is loaded, then modify your manifest:
"content_scripts": {
...
"run_at": "document_start"
Just to add a little more for anyone looking for an answer regarding the other scripts, as well as other methods for extension script access.
You can access the rest of the extension's scripts using the chrome.extension methods, as well as the chrome.runtime communication methods.
To get an array of all of the scripts from an extension, you can use the extension.getViews method.
You can also grab the background script, or a specific background script with the getBackgroundPage method.
Another option is to use message passing to pass the contents of a script with the runtime.sendMessage method, and using an event listener on another script to listen for runtime.onMessage allowing the script to receive the data from the sending script.
In addition to the previous option, you can use also use message passing to receive scripts from another active extension sending with runtime.sendMessage, but this time using an event listener with the runtime.onMessageExternal instead (Cannot be used in Content Scripts).
I hope this helps someone, as much as it would have helped me earlier on.
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