本文介绍了扩展程序将停止在browser.browserAction.onClicked.addListener(funct);上执行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我的浏览器扩展很简单,但是清单存在问题.在一种情况下,仅浏览器按钮有效,而在另一种情况下,仅脚本有效.

My browser extensions is simple one so far but there is an issue with manifest. In one case only browser button works, and on the other only script works.

background.js

background.js

function myfunction() { //change page text }
myfunction();

function onclicktest() { // do something on btn click }

browser.browserAction.onClicked.addListener(onclicktest);

alert('Never shown');

案例1-浏览器按钮不起作用,调用了myfunction

Case 1 - Browser button not working, myfunction gets called

"content_scripts":
[{
  "matches": ["<all_urls>"],
  "js": ["background.js"],
  "run_at": "document_end"
}]

案例2-浏览器按钮正常工作,myfunction未被调用

Case 2 - Browser button working, the myfunction doesn't get called

"background": {
    "scripts": ["background.js"]
}

这是Firefox插件.

This is a Firefox add-on.

推荐答案

这是因为 browserAction API对内容脚本环境和 myfunction 中的代码不可用在扩展程序的后台脚本中执行该操作后,原本应该用来修改网页的功能将无法正常工作.

That is because the browserAction API is not available to the content script environment and the code from myfunction that is supposed to modify a web page won't work when it is executed in the extension's background script.

您可以使用以下方法进行这项工作:

You could make this work using something like this:

browser.browserAction.onClicked.addListener(function(tab){
    chrome.tabs.executeScript(tab.id, {
        code: `(${myfunction.toString()})();`
    }
});

还有manifest.json:

And the manifest.json:

"permissions":["tabs"],
"background": {
    "scripts": ["background.js"]
}

这篇关于扩展程序将停止在browser.browserAction.onClicked.addListener(funct);上执行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:27