c0rv0s
c0rv0s

Reputation: 351

A way to activate a script on a tab in FireFox when a specific URL is opened

As the title says, I need my addon to execute a script that will inject some CSS when a specific URL is opened. How would one go about calling on a script to run?

Upvotes: 1

Views: 86

Answers (1)

Makyen
Makyen

Reputation: 33306

Assuming that you are using the add-on SDK, this is done by using page-mod (documentation on MDN).

The page I have linked to on MDN has a considerable amount of information on the subject of using page-mod. Quoting from that page:

page-mod:
Run scripts in the context of web pages whose URL matches a given pattern.

Usage:

To use page-mod, you specify:

  • one or more scripts (or other things, e.g. CSS) to attach. The SDK calls these scripts "content scripts".
  • a pattern that a page's URL must match, in order for the script(s) to be attached to that page.

For example, the following add-on displays an alert whenever the user visits any page hosted at "mozilla.org":

var pageMod = require("sdk/page-mod");

pageMod.PageMod({
  include: "*.mozilla.org",
  contentScript: 'window.alert("Page matches ruleset");'
});

For your specific desire to inject CSS, you would use either of the following two options to the page-mod constructor:

  • contentStyle: Lists stylesheets to attach, supplied as strings.
  • contentStyleFile: Lists stylesheets to attach, supplied in separate files.

You wanted to know how to execute a script. You wanted the script to inject CSS, but that is done directly with the options above rather than having a script do it. However, if you wanted to inject a script file to perform additional tasks, you would use the contentScriptFile option.

Upvotes: 1

Related Questions