0

My minimal failing example of JavaScript for a Mozilla/Firefox extension using a content script adds a paragraph to web pages and tries to register a function i_clicked() to be called when the user clicks there.

console.log("step 0");

function i_clicked() {
    console.log("step 2");
}

console.log("step 1");

let p = document.createElement("p");
p.textContent = "Click here";
p.setAttribute("onClick", "i_clicked()");
document.body.appendChild(p);

The log shows "step 0" and "step 1", but when I click on the paragraph, the console says: Uncaught ReferenceError: i_clicked is not defined. I conclude that the page cannot access the function I defined in the content script. How should this be done instead?

  • Have you tried using standard APIs instead? [`addEventListener`](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener). – Sebastian Simon Oct 30 '22 at 17:48
  • @SebastianSimon, yes, `p.addEventListener("onclick", i_clicked);` instead of setting the `onClick`. Then just nothing happens when I click, not even an error. Also with `"onClick"`. ´ – Bernhard Bodenstorfer Oct 30 '22 at 17:57
  • The event name is `click`, not `onclick`. – Sebastian Simon Oct 30 '22 at 18:17
  • @SebastianSimon, thanks, this gets me one step furter, `p.addEventListener("click", i_clicked, true);` registers the function and clicking fires `"step 2"` once. However, the second click does not do anything again. – Bernhard Bodenstorfer Oct 30 '22 at 19:44
  • Although it is about Chome extensions, the problem is so similar that I add here a reference to https://stackoverflow.com/questions/5162520/function-not-defined-creating-a-chrome-extension-content-script – Bernhard Bodenstorfer Nov 05 '22 at 19:05

1 Answers1

0

The suggestions by Sebastian Simon in the original comments seem to do the trick.

Here's an example manifest.json:

{
    "name": "OnClick demo",
    "description": "From Stack Overflow question",
    "version": "1.0.0",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]
}

and content.js

console.log("step 0");

function i_clicked() {
    console.log("step 2");
}

console.log("step 1");

let p = document.createElement("p");
p.textContent = "Click here";
p.addEventListener('click', i_clicked);
document.body.appendChild(p);

Here, I changed your original p.setAttribute("onClick", "i_clicked()"); into p.addEventListener('click', i_clicked);

When loaded as a temporary add-on on Firefox, I can see the click being activated each time.

console output saying "step 2" and having been run 8 times

Hamatti
  • 1,210
  • 10
  • 11