Javascript Button onClick not working in Chrome extension popup

只谈情不闲聊 提交于 2019-12-25 06:35:13

问题


(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?


回答1:


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.




回答2:


I think you should do that:

<button class="ui fluid red button" onclick="toggleActive()" id="toggle">Toggle Active</button>

You forget the parentheses after onclick.



来源:https://stackoverflow.com/questions/36317641/javascript-button-onclick-not-working-in-chrome-extension-popup

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