Skip to content Skip to sidebar Skip to footer

Chrome Extension - Js Function Is Unrecognizable

I'm new to chrome extensions development. I'm trying to build a very basic extension just to see how things work. The extension I want to build needs to add a button along with all

Solution 1:

There are many problems here, but let's start with the most important one.

Chrome extensions have their content scripts live in an isolated environment.

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

When you create an element with an inline code attached to it (onclick as a parameter of the element), that code lives in the page's context.

Since the context is isolated from your content script, myFunction is not defined in it.

The correct way to do it here is to avoid inline scripting altogether and attach listeners using addEventListener.


That said, the next problem: you're manipulating innerHTML to add DOM. That's a thoroughly bad idea, as you're potentially destroying state information.

Here's what element.innerHTML += "something" does:

  1. Convert element's contents into a string representing the DOM nodes. This discards anything that was attached to DOM nodes afterwards - like event listeners.
  2. Add "something" to that string.
  3. Discard all DOM nodes inside element.
  4. Replace element's contents with DOM generated from the result string.

Do not potentially destroy someone else's (or your own) work. Use proper DOM manipulation that doesn't go through conversion to string: create a node, and insert (append) it to the node you want.

var button = document.createElement("button");
button.text = "Click me";
button.addEventListener("click", myFunction);
element.appendChild(button);

Finally, you expect for some reason that element will be passed to myFunction. Event listeners indeed receive an argument, but instead it's the Event object. You can use its target attribute, or, if I remember correctly, even this inside the listener:

functionmyFunction(e) { // e is the eventconsole.log(e.target);
  console.log(this);
}

Post a Comment for "Chrome Extension - Js Function Is Unrecognizable"