我不能 100% 确定您的问题是否真的仅限于查找 bookmarksPanel。因此,此答案包含有关访问 bookmarksPanel、查看 DOM、从覆盖或无重启扩展访问侧边栏以及获取 window 参考的一般信息。
访问bookmarksPanel
以下内容应该让您参考<page id="bookmarksPanel">:
var sidebarDocument = document.getElementById("sidebar").contentDocument;
var bookmarksPanelElement = sidebarDocument.getElementById("bookmarksPanel")
请注意,您需要在sidebarDocument 中使用getElementById(),而不是不会搜索到侧边栏的主要window.document.getElementById()。
查看 DOM
如果您在了解特定元素的 DOM 结构时遇到问题,我建议您安装 DOM Inspector (for SeaMonkey)(查看 DOM)和 Element Inspector(允许您转移- 右键单击一个元素并打开该元素上的 DOM 检查器)。
这是 DOM Inspector 在 Firefox 中查看书签侧边栏的示例:
从 Overlay 或 Restartless 扩展访问侧边栏
引用 MDN:“Sidebar: Accessing the sidebar from a browser.xul script”:
从 browser.xul 脚本访问侧边栏
侧边栏内容始终位于与主浏览器文档分开的文档中(侧边栏实际上是作为 XUL 浏览器元素实现的)。这意味着您无法从 browser.xul 覆盖层引用的脚本直接访问侧边栏内容。
要访问侧边栏的窗口或文档对象,您需要分别使用document.getElementById("sidebar") 的contentWindow 或contentDocument 属性。例如,下面的代码调用了在侧边栏上下文中定义的函数:
var sidebarWindow = document.getElementById("sidebar").contentWindow;
// Verify that our sidebar is open at this moment:
if (sidebarWindow.location.href ==
"chrome://yourextension/content/whatever.xul") {
// call "yourNotificationFunction" in the sidebar's context:
sidebarWindow.yourNotificationFunction(anyArguments);
}
根据您当前运行的代码的启动方式(例如 UI 按钮),您可能需要获取当前浏览器 window。
大量复制another answer of mine,您可以通过以下方式获得:
获取对最新window的引用:
Firefox 附加组件通常在未定义全局 window 对象的范围内运行(是否已定义取决于当前运行的代码部分是如何输入的)。即使已定义,它通常也不会定义为您所期望的window(当前选项卡的window)。您可能需要为最近访问的窗口/选项卡获取对 window 对象的引用。
如果存在浏览器窗口(在某些情况下,您可能在不存在浏览器窗口的情况下运行,例如在启动时),您可以获得对最新浏览器 window、document 和gBrowser 与:
if (window === null || typeof window !== "object") {
//If you do not already have a window reference, you need to obtain one:
// Add/remove a "/" to comment/un-comment the code appropriate for your add-on type.
/* Add-on SDK:
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
//* Overlay and bootstrap (from almost any context/scope):
var window=Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//*/
}
if (typeof document === "undefined") {
//If there is no document defined, get it
var document = window.content.document;
}
if (typeof gBrowser === "undefined") {
//If there is no gBrowser defined, get it
var gBrowser = window.gBrowser;
}
如果您正在运行代码以响应事件(例如按钮command 事件),您可以通过以下方式获取当前window:
var window = event.view
缺少可用的全局window 对象,或者它引用的内容与您的预期不同,这是许多人在编写 Firefox 插件时遇到的问题。
注意:如果您希望与multi-process Firefox(Electrolysis,或 e10s)原生兼容,那么获取对当前文档内容的访问权限会更加复杂。有一些 shims 可以让您的代码在多进程 Firefox 中继续工作一段时间,但它们可能/将会最终消失。
参考资料:
nsIWindowMediator
- Working with windows in chrome code
- SDK:window/utils
- SDK:windows
- Multiprocess Firefox
- Working with multiprocess Firefox
其中大部分内容是从我之前的答案中复制而来的,包括this link。