[英]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. 我正在编写一个Firefox扩展(附加组件),允许用户使用文本和/或绘图注释任何页面,然后保存包含注释的页面图像。 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.
用例将是客户审查网页,向页面添加反馈,保存图像并通过电子邮件将其发送回Web开发人员或测试人员获取GUI错误的注释截图等。
I wrote the annotation/drawing functionality in javascript before developing the extension. 我在开发扩展之前在javascript中编写了注释/绘图功能。 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 eg line, box, ellipse, text, etc. This works fine when manually included in a page. 此脚本将
<canvas>
元素添加到要绘制的页面以及包含按钮(每个<canvas>
元素)的工具栏(在<div>
),用于不同的绘制工具,例如line,box,ellipse,text,当手动包含在页面中时,此工作正常。
I now need a way for the extension to: 我现在需要一种扩展方式:
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. init()
函数在这个脚本中添加画布和工具栏元素等需要以某种方式运行,但我无法确定如何从扩展名调用它。 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). 请注意,一旦注入,我不需要此脚本与扩展交互(因为当用户按下扩展名chrome中的保存按钮时,扩展只会获取整个文档的屏幕截图(并删除添加的页面元素))。
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. 这就是我通过设置onload属性来调用脚本中的init函数来解决我的问题的方法。
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);
Use the Greasemonkey extension : 使用Greasemonkey扩展 :
Allows you to customize the way a web page displays or behaves, by using small bits of JavaScript.
允许您使用少量JavaScript自定义网页显示或行为的方式。
Hundreds of scripts, for a wide variety of popular sites, are already available at http://userscripts.org .
http://userscripts.org上已有数百个用于各种热门网站的脚本。
You can write your own scripts, too.
您也可以编写自己的脚本。 Check out http://wiki.greasespot.net/ to get started.
查看http://wiki.greasespot.net/即可开始使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.