我正在学习如何制作chrome扩展,我正在做的项目是一个新标签中的“时钟”。
问题:我可以检索当前时间,但不能每秒刷新页面。我该如何解决这个问题呢?
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>发布于 2021-09-11 20:59:49
我选择了setTimeout,允许时钟每秒刷新一次,只有在页面加载之后才会发生。
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);https://stackoverflow.com/questions/69146408
复制相似问题