Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including Javascript files in a Chrome extension content script

I'm writing a Chrome extension, and want to write one JS file, that provides several expected functions that aren't present in another, then load that other file. I'm after behavior similar to require in Perl, #include in C, or execfile in Python when passing the current modules locals and globals, as though the referenced file was inserted directly into the current script.

Most existing solutions I can find out there refer to embeddeding these "includes" inside script tags, but I'm not sure this applies (and if it does, an explanation of where exactly my extension is injecting all these script tags in the current page).

Update0

Note that I'm writing a content script. At least on the "user" side, I don't provide the original HTML document.

like image 562
Matt Joiner Avatar asked Sep 28 '10 14:09

Matt Joiner


People also ask

How do you include a JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can you include one JavaScript file in another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

Where should I put my JavaScript files?

To place JavaScript in an HTML file, use the <script>… </script> tag. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.


1 Answers

Well the best solution was Chrome-specific. The javascript files are listed in the order they are loaded in the extension's manifest.json, here's an extract of the relevant field:

{
  "content_scripts": [
    {
      "js" : ["contentscript.js", "254195.user.js"]
    }
  ]
}

The javascript files are effectively concatenated in the order given and then executed.

like image 50
Matt Joiner Avatar answered Oct 18 '22 19:10

Matt Joiner