移动Firefox(Fennec)附加组件:在页面加载时执行代码

时间:2011-07-14 14:48:14

标签: mobile firefox-addon fennec

我正在尝试编写一个移动firefox插件,每次加载页面时都会自动执行一段javascript代码。我已经为早期版本的Fennec编写了一些代码,但是使用更新的Fennec版本(https://wiki.mozilla.org/Mobile/Fennec/Extensions/Electrolysis/)中的多处理系统,此代码必须是移植。我基于http://people.mozilla.com/~mfinkle/tutorials/的教程,使用一个版本工作,只要在浏览器菜单中选择了一个选项,就会执行一段代码。该解决方案由两部分组成,即overlay.js(用于主(应用程序)进程)和content.js(用于子(内容)进程)。 Overlay.js在overlay.xul中加载,而content.js通过overlay.js中的以下代码加载到新标签:

window.messageManager.loadFrameScript("chrome://coin/content/content.js", true);

只要单击浏览器菜单中的选项,overlay.js中的代码就会向content.js发送一条消息,然后正确执行所需的代码(一些脚本标记只是添加到页面的头部)。但是,我不知道如何在页面加载时自动执行代码。我在content.js中尝试了以下内容:

function addCoin(aMessage) { ... }

// this executes the desired code every time an option is clicked in the browser menu
addMessageListener("coin:addCoin", addCoin);

// this attempts to execute the code on every page load; i.e., after this script has     
been loaded for the new tab
addCoin(null);

然而最后一句话没有效果。然后,我尝试在最后添加以下语句:

sendAsyncMessage("coin:scriptLoaded", { });

该语句向overlay.js脚本发送一条消息,该脚本为该消息注册一个监听器,并且作为响应,只发送与点击浏览器菜单中的选项时相同的消息,即“coin:addCoin”。但是,这也不起作用。最后,我尝试查找overlay.js脚本可以侦听的某些事件(类似“tabOpened”或类似内容),但找不到任何内容。

有没有人对如何在每次加载页面时自动执行代码有任何想法?

此致

威廉

2 个答案:

答案 0 :(得分:3)

在你的content.js脚本中,你可以简单地为“load”事件注册一个事件监听器,就像在旧的单个进程Firefox中一样:

addEventListener("load", someFunc, true);

只要在标签页中加载网页,就会调用“someFunc”。

content.js中的任何全局代码都是在初始创建选项卡时执行的,而不是在页面加载时执行的。使用全局代码设置事件侦听器或消息侦听器。 Web内容仍将触发您可以在content.js(子脚本)中捕获的事件。

答案 1 :(得分:1)

这对我有用。

content.js中的

var addEventListener;

if (window.BrowserApp) { // We are running in Mobile Firefox
    addEventListener = window.BrowserApp.deck.addEventListener;
} else {
    var appcontent = document.getElementById("appcontent");
    if (appcontent) {
        addEventListener = appcontent.addEventListener;
    }
}

if (addEventListener) {

    var onDOMContentLoaded = function() { /* Code here */ };
    addEventListener("DOMContentLoaded", onDOMContentLoaded, true);

    var onLoad = function() { /* Code here */ };
    addEventListener("load", onLoad, true);

    // etc ...
}
相关问题