Home > Web Front-end > JS Tutorial > Why Aren\'t My Chrome Extension Popup Click Events Working?

Why Aren\'t My Chrome Extension Popup Click Events Working?

Susan Sarandon
Release: 2024-12-06 01:18:10
Original
404 people have browsed it

Why Aren't My Chrome Extension Popup Click Events Working?

Fixing Chrome Extension Popup Issues: Handling Click Events

When creating a Chrome extension popup with JavaScript, users may encounter issues where click events are not handled correctly. This can be due to violations of the default Content Security Policy (CSP).

Problem Description:

A developer has created a JavaScript variable and a button within the extension's popup. Upon clicking the button, the variable is expected to increment by 1. However, the code is not functioning as intended.

Manifest.json Configuration:

{
  "name":"Facebook",
  "version":"1.0",
  "description":"My Facebook Profile",
  "manifest_version":2,
  "browser_action":{
    "default_icon":"google-plus-red-128.png",
    "default_popup":"hello.html"
  }
}
Copy after login

Popup Page HTML:

<!DOCTYPE html>
<html>
<head>
  <script>
    var a=0;
    function count()
    {
      a++;
      document.getElementById("demo").innerHTML=a;
      return a;
    }
  </script>
</head>
<body>
  <p>
Copy after login

Explanation:

The issue arises due to the presence of inline JavaScript in the HTML file. Inline JavaScript is prohibited by the default CSP.

Solution:

To solve this problem, move all inline JavaScript to a separate JS file.

hello.html (Popup Page):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <p>
Copy after login

popup.js:

var a = 0;

function count() {
  a++;
  document.getElementById('demo').textContent = a;
}

document.getElementById('do-count').onclick = count;
Copy after login

Additional Note:

Use textContent instead of innerHTML when modifying text content to prevent potential security vulnerabilities.

The above is the detailed content of Why Aren\'t My Chrome Extension Popup Click Events Working?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template