Javascript[Chrome扩展]开发中如何使用setInterval
How to use setInterval in Javascript [Chrome Extension] development
我正在学习如何制作 chrome 扩展,我正在处理的项目是 'Clock' 在新选项卡中。
问题:我能够检索当前时间,但无法每秒刷新页面。
我该如何解决这个问题?
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>
我选择了 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);
我正在学习如何制作 chrome 扩展,我正在处理的项目是 'Clock' 在新选项卡中。
问题:我能够检索当前时间,但无法每秒刷新页面。 我该如何解决这个问题?
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>
我选择了 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);