Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension referencing/calling other script functions from a content script

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

like image 535
TheGeneral Avatar asked Oct 31 '13 21:10

TheGeneral


2 Answers

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"
like image 192
gkalpak Avatar answered Sep 30 '22 14:09

gkalpak


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.

  1. To get an array of all of the scripts from an extension, you can use the extension.getViews method.

  2. You can also grab the background script, or a specific background script with the getBackgroundPage method.

  3. 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.

  4. 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.

like image 30
DBrown Avatar answered Sep 30 '22 13:09

DBrown