Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject javascript into page, from a Firefox add-on, and run it?

I'm writing a Firefox extension (add-on) to allow users to annotate any page with text and/or drawings and then save an image of the page including the annotations. Use cases would be clients reviewing web pages, adding feedback to the page, saving the image of this and emailing it back to the web developer or testers taking annotated screenshots of GUI bugs etc.

I wrote the annotation/drawing functionality in javascript before developing the extension. This script adds a <canvas> element to the page to draw upon as well as a toolbar (in a <div>) that contains buttons (each <canvas> elements) for the different draw tools e.g. line, box, ellipse, text, etc. This works fine when manually included in a page.

I now need a way for the extension to:

  1. Inject this script into any page, including pages I don't control.
  2. This needs to occur when the user invokes the extension, which can be after the page has loaded.
  3. Once injected the init() function in this script that adds the canvas and toolbar elements etc. needs to be run somehow, but I can't determine how to call this from the extension.

Note that once injected I don't need this script to interact with the extension (as the extension just takes a screenshot of the entire document (and removes the added page elements) when the user presses the save button in the extension chrome).

like image 466
el griz Avatar asked Dec 23 '22 02:12

el griz


2 Answers

So this is how I solved my problem by setting the onload attribute to call the init function in the script that's being appended to the page.

var myScript = top.window.content.document.createElement('script');
myScript.type = 'text/javascript';
myScript.setAttribute('src','chrome://path/to/script.js');
myScript.setAttribute('onload', 'firefoxInit()');
top.window.content.document.getElementsByTagName('head')[0].appendChild(myScript);
like image 184
el griz Avatar answered May 09 '23 07:05

el griz


Use the Greasemonkey extension :

Allows you to customize the way a web page displays or behaves, by using small bits of JavaScript.

Hundreds of scripts, for a wide variety of popular sites, are already available at http://userscripts.org.

You can write your own scripts, too. Check out http://wiki.greasespot.net/ to get started.

like image 45
Martin Schlatter Avatar answered May 09 '23 08:05

Martin Schlatter