Onclick or Inline Script Isn't Working in Extension

onclick or inline script isn't working in extension

Chrome Extensions don't allow you to have inline JavaScript (documentation).

The same goes for Firefox WebExtensions (documentation).

You are going to have to do something similar to this:

Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), and use addEventListener to bind the event. Put the following in your popup.js file:

document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});

popup.js should be loaded as a separate script file:

<script src="popup.js"></script>

Chrome extension: onclick() event is not triggering an alert() popup

Don't use inline JavaScript code in a Google Chrome extension.

HTML:

<div class="plus"></div>
<script src="inline.js"></script>

JavaScript:

function popup(e) {
var link = document.URL;
alert("This is the link: (" + link + ")");
}

var plusBtn = document.querySelector('.plus');
plusBtn.addEventListener('click', popup);

Functions aren't working in Chrome Extension

As stated by @Deliaz in the comments, inline javascript isn't allowed in chrome extension because of strict environment isolation.

Change this: <button onclick="search()">Search</button> to: <button id='searchButton'>Search</button>

and place some code in your separate script.js file that attaches an eventlistener to your search button on the click action.

// Triggers when all DOM elements are loaded
document.addEventListener('DOMContentLoaded', function(event) {
// Attaches listener for click event on search button
document.querySelector('#searchButton').addEventListener('click', function(e) {
return search();
});
});

function search() {
var text = document.getElementById("searchBar").value;
window.open("https://www.google.com/search?q=" + text)
}

Alternatively you could also use the search event on the input field: https://developer.mozilla.org/en-US/docs/Web/Events/search



Related Topics



Leave a reply



Submit