I'm making a firefox extension which displays a stopwatch at the top of specific websites. I also have a button that resets the stop watch to 00:00:00. I want the extension to automatically reset the timer whenever any function in that website is called.
For example, if a website has a button which changes the website's background color, then every time that button is clicked the timer should reset.
How do I access the functions of various websites in my extension? Also do I have to change the manifest.json file (permissions and stuff)? And once I access them how can I make an eventlistener for every single one of them?
This is my manifest.json file
{
"name": "timer",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"],
"css":["style.css"]
}
],
"manifest_version": 2
}
My javascript
var tim = document.createElement('time');
var button = document.createElement("button");
button.innerHTML = "RESET";
tim.innerText = "00:00:00"
document.body.insertAdjacentElement('beforebegin', tim);
document.body.insertAdjacentElement('beforebegin', button);
button.addEventListener ("click", function() {
tim.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
});
//when anything in body changes
let Par = document.body,
options = {
attributes: true
},
observer = new MutationObserver(restart);
var h1 = document.getElementsByTagName('time')[0],
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
tim.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
//restart method that resets timer
function restart() {
tim.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
observer.observe(Par, options);
Thanks!
EDIT: following @wOxxOm advice, I have tried tracking any changes in body using MutationObserver. The way I have done it must be wrong because it's not working properly. To reiterate, what I want is when any changes in the body happens then the timer resets. Any idea on why the way I did it is wrong? I am quite new with javascript and haven't used MutationObserver before so I really have no idea