我需要它在我的 Firefox 扩展中使用。
我已经尝试过 window.onload
事件监听器,并检查当前 url == 旧 url,这是个好主意,但是当页面加载 PDF 时它不起作用。
我也看到了 hash changed 函数,但它只适用于 Firefox 3.6;我需要它至少与 Firefox 3 一起工作。
所以,我需要一个事件监听器来检查 document.location
是否更改。
最佳答案
例如,您可以使用:
var mainWindow = window
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem).rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.getBrowser().addEventListener("DOMContentLoaded",
your_function, false);
但是,重点是,您需要将监听器添加到浏览器,而不是窗口。
编辑
参见 https://developer.mozilla.org/En/Code_snippets/Tabbed_browser有关从不同上下文访问浏览器的信息,以及一些其他有用的信息。
编辑
只是为了添加更多细节....
function your_function(event) {
if (event.originalTarget instanceof HTMLDocument) {
var doc = event.originalTarget;
// if it's just a frame element, then return and wait for the
// main event to fire.
if (event.originalTarget.defaultView.frameElement)
return;
// now you can use doc.location however you want
}
}
请注意,这将响应在任何选项卡中打开的页面,而不是特定选项卡。
对于特定的标签,你可以使用这样的东西:
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
newTabBrowser.addEventListener("load", function () {
newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>";
}, true);
上面添加了一个新的选项卡,然后添加了一个监听器。但是,对于所有选项卡,您都需要如下内容。然后在添加时在每个选项卡上添加“DOMContentLoaded”事件监听器(并在关闭时删除)。
您可能还想查看:https://developer.mozilla.org/En/Code_snippets/Tabbed_browser#Notification_when_a_tab_is_added_or_removed和 https://developer.mozilla.org/En/Code_snippets/Tabbed_browser#Getting_document_of_currently_selected_tab
(为了保存)
function exampleTabAdded(event) {
var browser = gBrowser.getBrowserForTab(event.target);
// browser is the XUL element of the browser that's been added
}
function exampleTabMoved(event) {
var browser = gBrowser.getBrowserForTab(event.target);
// browser is the XUL element of the browser that's been moved
}
function exampleTabRemoved(event) {
var browser = gBrowser.getBrowserForTab(event.target);
// browser is the XUL element of the browser that's been removed
}
// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabClose", exampleTabRemoved, false);
// When no longer needed
container.removeEventListener("TabOpen", exampleTabAdded, false);
container.removeEventListener("TabMove", exampleTabMoved, false);
container.removeEventListener("TabClose", exampleTabRemoved, false);
这应该让您完成了 99% 的事情。
关于javascript - 如何检查当前浏览器选项卡的 url 是否已更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2060779/