When attempting to add custom emotes to a website using a userscript, you may encounter an error stating, "Uncaught ReferenceError: function is not defined" upon clicking a button with an onclick attribute.
Userscripts operate in a sandboxed environment, preventing direct access to functions existing within the target web page's scope. The onclick attribute utilizes this web page scope, causing it to fail when used in a userscript.
To resolve this issue, avoid using onclick() and similar attributes in userscripts. Instead, opt for the addEventListener() method (or equivalent library function such as jQuery .on() for this purpose.
For instance, the following code using onclick:
something.outerHTML += '<input onclick="resetEmotes()">
Can be rewritten using addEventListener():
something.outerHTML += '<input>
Additionally, avoid passing data directly to event listeners using code like this:
emoteTab[2].innerHTML += '<span>
Instead, use data attributes and add event listeners separately, as seen below:
for (i = 0; i < EmoteURLLines.length; i++) { if (checkIMG(EmoteURLLines[i])) { emoteTab[2].innerHTML += '<span>
In the appendEmote function:
function appendEmote(zEvent) { var emoteUsage = this.getAttribute("data-usage"); shoutdata.value += emoteUsage; }
Avoid reusing the same ID for multiple elements as it's invalid. Each page can have only one instance of a particular ID.
Also, be cautious about using .outerHTML or .innerHTML as they remove existing event handlers from affected nodes.
The above is the detailed content of Why Does My Userscript Get an \'Uncaught ReferenceError: Function Not Defined\' Error When Using onclick, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!