Currently, I am creating a WebExtension for Firefox which displays a small div in the active HTML page on the active tab after 6 seconds (not the popup.html in browser_action
!). I made a small example that shows a button in the div. My problem is that I don't know how to detect a click
event of this button so I can kick off a function? In the moment I handle the event listener in content.js
manifest.json:
{
"manifest_version": 2,
"name": "Study06",
"version": "1.0",
"description": "My web extension",
"permissions": [
"tabs",
"<all_urls>",
"alarms"
],
"background": {
"scripts": ["background.js"]
}
}
background.js:
browser.alarms.create("", {delayInMinutes: 0.1});
browser.alarms.onAlarm.addListener(injectScript);
function getActiveTab() {
return browser.tabs.query({active: true, currentWindow: true});
}
function injectScript() {
getActiveTab().then((tabs) => {
browser.tabs.executeScript(null, {
file: "/content.js"
});
// send message to contentscript
browser.tabs.sendMessage(tabs[0].id, {message: "Hello"});
});
}
After 6 seconds, content.js will be loaded and a message to content.js will be sent.
content.js:
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('button_id');
button.addEventListener('click', function() {
console.log("CLICK");
});
});
browser.runtime.onMessage.addListener(createModal);
function createModal(){
document.getElementsByTagName('body')[0].appendChild(modal1);
}
//create div with button
var modal1 = document.createElement("div");
modal1.style.paddingTop = "100px";
modal1.setAttribute("id", "mymodal1");
modal1.style.position = "fixed";
modal1.style.top = 0;
modal1.style.left = 0;
modal1.style.zIndex = 1000000;
modal1.style.overflow = "auto";
var button1 = document.createElement("button");
button1.setAttribute("id", "button_id");
button1.innerHTML = "Click me";
modal1.appendChild(button1);
The event listener in content.js is not working.
I also created a JavaScript file javascriptForButtonEvent.js with an event listener for the button and added this script in manifest content_script
. Also, to inject this file in background script like:
browser.tabs.executeScript(null, {
file: "/content.js";
file: "/javascriptForButtonEvent.js"
});
But, these solutions didn't work for me (when clicking the button nothing happens). Is there a way to handle events from the active HTML page?