I'm learning how to make chrome extensions and the project that I'm working on is a 'Clock' in a new tab.
Issue: I'm able to retrieve the current time, but I'm unable to refresh the page every second. How can I fix this?
main.js
setInterval(function () {
var d = new Date();
const h = d.getHours();
const m = d.getMinutes();
const s = d.getSeconds();
// Current Time w/ format
const cFormat = h + ":" + m;
const cTime = document.getElementById("cTime");
cTime.textContent = cFormat;
}, 1000);
manifest.json
{
"manifest_version": 3,
"name": "ClockTab",
"description": "Clock.",
"version": "1.0.0",
"persistent": true,
"icons": {"128": "icon_128.png"},
"host_permissions": ["<all_urls>","activeTab","tabs"],
"action" : {
"default_popup": "popup.html",
"default_icon": "icon_128.png"
},
"chrome_url_overrides" : {
"newtab": "index.html"
},
"background": {
"service_worker": "main.js",
},
"content_scripts": [{
"css": ["style.css","popup.css"],
"js": ["jquery.min.js", "main.js", "popup.js","dateTime.js"],
"all_frames": true,
"matches": ["http://*/*"]
}]
}
index.html
<div id="cTime"></div>
I opted for setTimeout allowing for the clock to refresh every second which only occurs after the page loads.
main.js
function start() {
// Clock
function getTime() {
var d = new Date();
const h = d.getHours();
const m = d.getMinutes();
const s = d.getSeconds();
// Current Time w/ format
const cFormat = h + ":" + m;
const cTime = document.getElementById("cTime");
cTime.textContent = cFormat;
setTimeout(function () {
getTime();
}, 1000);
}
getTime();
}
window.addEventListener("load", start);