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
Susan SarandonOriginal
2024-12-06 01:18:10399browse

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"
  }
}

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>

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>

popup.js:

var a = 0;

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

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

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!

Statement:
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