简体   繁体   中英

Javascript Button onClick not working in Chrome extension popup

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

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.

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