onclick or inline script in Extension does not work
Problem:
in extension , the onClick function fails to perform its intended function, although in stock browsers it works fine.
Code example:
function hellYeah(text) { document.getElementById("text-holder").innerHTML = text; }
<!doctype html> <html> <head> <title>Getting Started Extension's Popup</title> <script src="popup.js"></script> </head> <body> <div>
When the user clicks "hyhy", "ha" should change to "xxx", but in the extension it doesn't doesn't work.
Answer:
Chrome extensions and Firefox WebExtensions do not allow inline JavaScript. Therefore, you need to use other methods to bind events.
One way is to assign an ID to the link (for example, ) and bind the event using addEventListener in the popup.js file:
document.addEventListener('DOMContentLoaded', function() { var link = document.getElementById('link'); // 点击逻辑如下: link.addEventListener('click', function() { hellYeah('xxx'); }); });
Make sure popup.js Loaded as a separate script file:
<script src="popup.js"></script>
The above is the detailed content of Why Doesn't My Inline onclick Function Work in a Chrome/Firefox Extension?. For more information, please follow other related articles on the PHP Chinese website!