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

I am writing a Firefox extension (add-on) so that users can annotate any page with text and / or drawings, and then save the page image, including annotations. Use cases will be customers browsing the web, adding feedback to the page, saving an image of it, and sending it by email to a web developer or testers with annotated screenshots of GUI errors, etc.

I wrote an annotation / drawing function in javascript before developing the extension. This script adds the <canvas> to the page for drawing, as well as a toolbar (in the <div> ) that contains buttons (each <canvas> ) for various drawing tools, for example. string, field, ellipse, text, etc. This works great for manual inclusion on the page.

Now I need an extension method:

  • Paste this script on any page, including pages that I do not control.
  • This should happen when the user calls the extension, which may be after the page loads.
  • After entering the init() function in this script, which adds the elements of the canvas and toolbar, etc., it should be run somehow, but I cannot determine how to call this from the extension.

Please note that after entering I do not need this script to interact with the extension (since the extension simply takes a screenshot of the entire document (and deletes the added page elements) when the user clicks the save button in the chrome extension).

+4
source share
2 answers

So, this is how I solved my problem by setting the onload attribute to call the init function in the script that is added 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); 
+10
source

Use the Greasemonkey extension :

Allows you to customize the way your web page is displayed or maintained using small JavaScript fragments.

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

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

+2
source

Source: https://habr.com/ru/post/1310453/


All Articles