Home > Web Front-end > JS Tutorial > Why Doesn't My Inline onclick Function Work in a Chrome/Firefox Extension?

Why Doesn't My Inline onclick Function Work in a Chrome/Firefox Extension?

DDD
Release: 2024-12-28 10:09:15
Original
158 people have browsed it

Why Doesn't My Inline onclick Function Work in a Chrome/Firefox Extension?

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;
}
Copy after login
<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <div>
Copy after login

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');
    });
});
Copy after login

Make sure popup.js Loaded as a separate script file:

<script src="popup.js"></script>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template