Firefox WebExtention API: TypeError: browser.browserAction is undefined [duplicate]

匆匆过客 提交于 2019-11-27 07:10:46

问题


This question already has an answer here:

  • TypeError: [API] is undefined in content script or Why can't I do this in a content script? 2 answers

While migrating my old Firefox add-on to WebExtension API, failed to understand while I am getting this error:

TypeError: browser.browserAction is undefined

Here is the manifest.json:

{

  "manifest_version": 2,
  "name": "My Login",
  "version": "3.0",

  "description": "Login to my page",
  "homepage_url": "https://localhost",
  "icons": {
    "48": "icons/button-1.png"
  },

  "permissions": [
    "activeTab", "storage"
  ],

  "browser_action": {
    "default_icon": "icons/button-1.png",
    "default_title": "Login"
  },


  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["index.js"]
    }
  ],

  "options_ui": {
    "page": "options.html"
  }
    }

Here is the index.js:

function handleClick() {


    var loginUserName, loginPassword;

    var URL = window.content.location.href;

    var doc = window.content.document;


}

browser.browserAction.onClicked.addListener(handleClick);

So I am getting TypeError: browser.browserAction is undefined in the browser console when I go to about:debugging and load my add-on as a temporary addon.

Options.html, options.js and button-1.png do exist - I just don't place them here.

Observed in Firefox 55.0.3 (32-bit). Any idea why this error happens?

Thanks, Racoon


回答1:


browser.browserAction should be called in a background script and not in a content script like you're doing. So assuming this code is in background.js:

function handleClick() {
    console.log("do something.");
    // If you want to something with the content, you will need a content script and messaging
}

browser.browserAction.onClicked.addListener(handleClick);

You add the background_scripts key in manifest.json:

{

  "manifest_version": 2,
  "name": "My Login",
  "version": "3.0",

  "description": "Login to my page",
  "homepage_url": "https://localhost",
  "icons": {
    "48": "icons/button-1.png"
  },
  "background": {
    "scripts": ["background.js"]
  }
}


来源:https://stackoverflow.com/questions/46081284/firefox-webextention-api-typeerror-browser-browseraction-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!