I'm trying to write firefox extension which will run when a (specific) page is loaded (it will be same key words replace).
I write code like:
window.addEventListener("load", function() maApp.init(); }, false);
var maApp= {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", maApp.onPageLoad, true);
var messagepane = document.getElementById("messagepane"); // mail
if(messagepane)
messagepane.addEventListener("load", function(event) { maApp.onPageLoad(event); }, true);
},
onPageLoad: function() {
alert("test);
doSomething();
}
};
But onPageLoad is never run.开发者_如何学Go.. no alert... Can somebody please tell me what I'm doing wrong?
First some words on getting the browser element. In Firefox this element has ID content
, not appcontent
. Still, the recommended way of getting it is the window.gBrowser
variable. In Thunderbird 5 the ID of the browser element changed so your code will stop working - rather than going by ID you should use window.messageContent
variable which will work both in the current and future versions. Together you get:
var browser = null;
if ("gBrowser" in window)
browser = window.gBrowser; // Firefox and SeaMonkey Browser
else if ("messageContent" in window)
browser = window.messageContent; // Thunderbird
else if ("getMessageBrowser" in window)
browser = window.getMessageBrowser(); // SeaMonkey Mail
if (browser)
...
Now about listening to page loads, the recommended approach here is progress listeners - see https://developer.mozilla.org/en/Code_snippets/Progress_Listeners. You attach a progress listener to the browser and look for state changes:
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)
{
if ((aFlag & Components.interfaces.nsIWebProgressListener.STATE_STOP) &&
(aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW))
{
// A window finished loading
doSomething(aWebProgress.DOMWindow);
}
}
The accepted answer is outdated. The solution using the WebExtensions API would be
browser.tabs.onUpdated.addListener(function(tabId, changeInfo) {
if (changeInfo.status == "complete") {
//add your script
}
})
browser.tabs.onUpdated.addListener
Listens to events within the Tab (Reference)
(changeInfo.status == "complete")
filters the right event and executes the commands within the if statement.
精彩评论