Getting the contents of the toolbar search box usi

2019-08-07 17:49发布

问题:

I am developing a Firefox addon and I was wondering how to get the contents of the search box in the toolbar using the Mozila Addon SDK? I finally found the chrome URL where it resides (at least I think: chrome://browser/content/search/...), but I’m still a little unsure as to how to reference this to get the contents of the search box into my addon. I tried: document.getAnonymousElementByAttribute(this, "anonid", "searchbar-textbox"); but this gives a “document is not defined” error, probably because Firefox has no idea what ‘searchbar-textbox’ is and this is outside the scope of the addon (in a different ‘document’). I’m relatively new to addon development, so there’s probably a fairly straight forward way to do this, it is just that this solution is unknown to me. Thanks.

回答1:

Your "main" module (and other lib/ modules) do not have any document attached. You need to first use some low-level API such as the window/utils .getMostRecentBrowserWindow() function to obtain the DOMWindow for the active browser window. After that it's just getting the #searchbar element and checking the .value property (exposed through XBL).

Complete example:

const {getMostRecentBrowserWindow} = require("window/utils");

require("sdk/widget").Widget({
  id: "log-search-field",
  label: "Log Search Field",
  contentURL: "http://www.mozilla.org/favicon.ico",
  onClick: function() {
    let win = getMostRecentBrowserWindow();
    console.error("Search text: " + win.document.getElementById("searchbar").value);
  }
});