简体   繁体   中英

Firefox addon builder--can't get the content script to work

I have an addon with a button that opens a panel with a couple buttons. When a button is pressed, it's supposed to change the keyword.URL preference, but it isn't.

Here is the main.js:

data = require("self").data

var panel = require("panel").Panel({
  height: 135,
  width: 260,
  contentURL: data.url("popup.html"),
  contentScriptFile: data.url("clicklisten.js"),
  onMessage: function(contentScriptMessage) {
    require("preferences-service").set('keyword.URL', contentScriptMessage);
  }
  //I think the problem is right there, but i have no idea why.
});

var button = require("widget").Widget({
  id: "search-engine-button",
  label: "Set search engine",
  contentURL: data.url("Refresh.ico"),
  panel: panel
});

Here is a sample of the HTML buttons:

<button class="searchButton" id="addons" _keywordURL="https://addons.mozilla.org/en-US/firefox/search/?q=">Add-ons</button>

And this is clicklisten.js (the content script):

// Add event listener
var buttons = document.getElementByClassName("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"));
}

I feel like I have tried everything I can think of, but I can't get this to work.

It is generally a good first step to check the Error Console when searching bugs in extensions. If you press Ctrl-Shift-J to open it you should see:

Error: An exception occurred.
Traceback (most recent call last):
  File "resource://.../clicklisten.js", line 2, in 
    var buttons = document.getElementByClassName("searchButton");
TypeError: document.getElementByClassName is not a function

That's because the function is called getElementsByClassName (as s is missing). If you change to the correct name everything will work correctly.

PS: I thought that you copied that mistake from my answer to your previous question (I didn't test the code there). But looking at https://stackoverflow.com/a/10309914/785541 - it seems that you didn't, my code doesn't have this mistake :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM