问题
I am trying to make a button in the Firefox Add-on Builder that will change the URL that the searchbar uses. To change the URL, I have a panel that shows when the button is clicked, and in the panel is a series of buttons.
In a second .js file (not the main.js) I have the functions that are supposed to change the keyword.url function using the preferences-service module.
Here is the code I am using to do this:
function changekeywordurl(url) {
alert('Search Engine Changed');
require("preferences-service").set('keyword.url', url);
}
and the HTML for the panel is:
<button onclick="changekeywordurl('http://search.yahoo.com/search?p=')">Yahoo</button>
Sorry if I am making a really dumb mistake; this is my first attempt and an add-on.
回答1:
The HTML pages loaded by your extension don't have any special privileges - they are just like regular web pages. In particular, the function require() isn't defined in this context. What you need to do is to load a content script into the panel because a content script can communicate back to the extension. This content script could look like this:
// Add event listener in the content script, the page cannot "see" content script
// functions
var buttons = document.getElementsByClassName("searchButton");
for (var i = 0; i < buttons.length; i++)
buttons[i].addEventListener("click", changekeywordurl, false);
// Send a message to the extension if a button is clicked
function changekeywordurl(event)
{
var button = event.target;
self.postMessage(button.getAttribute("_keywordURL"));
}
And the button in the page would look like this:
<button _keywordURL="http://search.yahoo.com/search?p="></button>
Then your extension can listen to messages from the content script and use the necessary SDK modules.
来源:https://stackoverflow.com/questions/10306337/firefox-addon-builder-preferences-services-not-working-for-me-why