Javascript按钮onClick在Chrome扩展弹出式窗口中无法使用 [英] Javascript Button onClick not working in Chrome extension popup
问题描述
(link to git: https://github.com/Boundarybreaker/NameBlock )
我正在使用文本替换扩展,可以通过点击 popup.html
,但它只发生在我点击图标。 (视频: https://drive.google.com/file/d/ 0B_3pLT_KI8V8OHJFUHQ5a1JURkE / view?usp = sharing )
按钮的代码为< button class =ui fluid red button onclick = toggleActive()id =toggle>切换活动< / button>
和 toggleActive()
$ c> background.js ,以及侦听器 chrome.runtime.onMessage.addListener(toggleActive);
。如何让按钮正常工作?
onclick是一种内联脚本,因此在弹出窗口中禁止。
在您的popup.js中使用 myButton.addEventListener('click',toggleActive);
myButton
以任何常见的方式,通过添加一个id到它的html和使用 document.getElementById
$ c> getElementsByClassName,querySelectorAll 或任何其他方式。
toggleActive
.js可以发送消息到background.js,其中监听器将调用后台的 toggleActive
,或者您可以使用 chrome.runtime获取后台页面。 getBackgroundPage
或 chrome.extension.getBackgroundPage
(前者是async,后者是同步,返回窗口对象的背景),并调用你的背景 toggleActive
,如下所示:
var bkg = chrome.extenstion.getBackgroundPage
bkg.toggleActive();
也就是说,如果你真的需要在后台而不是弹出窗口中定义toggleActive。 p>
(link to git: https://github.com/Boundarybreaker/NameBlock)
I'm working on a text-replacement extension that can be toggled on and off with a button clicked in the popup.html
, but it only is happening when I click the icon. (video: https://drive.google.com/file/d/0B_3pLT_KI8V8OHJFUHQ5a1JURkE/view?usp=sharing)
The code for the button reads <button class="ui fluid red button" onclick=toggleActive() id="toggle">Toggle Active</button>
, and toggleActive()
is a function in background.js
, along with a listener chrome.runtime.onMessage.addListener(toggleActive);
. How would I get the button to work properly?
onclick is a kind of inline scripting, so it's forbidden in popup.
Use myButton.addEventListener('click',toggleActive);
in your popup.js
Obtain myButton
in any usual way, by adding an id to its html and using document.getElementById
, or by getElementsByClassName, querySelectorAll
or any other ways.
toggleActive
defined in popup.js can either send message to background.js, where the listener would call background's toggleActive
, or you can just get background page with chrome.runtime.getBackgroundPage
or chrome.extension.getBackgroundPage
(the former is async, the latter is sync, returning window object of background) and call your background toggleActive
from here, like this:
var bkg=chrome.extenstion.getBackgroundPage();
bkg.toggleActive();
That is, if you really need defining your toggleActive in background instead of popup.
这篇关于Javascript按钮onClick在Chrome扩展弹出式窗口中无法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!