问题描述
我正在尝试编写一个书签,当 GitHub 上的 CI 完成时,它会向我发送桌面通知。 Notification.requestPermission
运行正常,并要求我获得许可,console.log
语句运行正常,但未出现通知。这是书签脚本的文本:
(function() {
Notification.requestPermission().then(() => {
const search = setInterval(() => {
if (window.find("All checks have passed")) {
console.log('all checks passed');
clearTimeout(search);
new Notification('Github checks passed!');
} else {
console.log('checks pending');
}
},1000);
});
})();
即
javascript:(function() {Notification.requestPermission().then(() => {const search = setInterval(() => {if (window.find("All checks have passed")) {console.log('all checks passed');clearTimeout(search);new Notification('Github checks passed!');} else {console.log('checks pending');}},1000);});})();
这是沙盒游戏吗?
解决方法
我已尝试使用您编写的相同代码,并尝试添加一些调整并验证现有代码。
我发现您的代码没有问题。我曾尝试用您的代码模拟相同的情况,并且可以正常工作。
为了处理您的代码,我在页面加载 5 秒后在 HTML 正文中添加了虚拟文本,同时,setTimeout 函数记录了待处理的检查
5 秒后,它会在正文中输入一个文本,然后它会搜索文本并且代码工作正常。
这里是我的一些小调整,可以帮助您确定根本原因。我想如果您的代码正在处理这些调整,这意味着在您的真实情况下,可能无法从 HTML 模板中找到该文本。
是的,还有一件事你应该记住,当浏览器在弹出窗口中询问时,你必须允许通知,一旦你允许显示通知,在下次尝试时,它会用建议的文本填充通知。
以下代码,我试过了。
缩小版本:
javascript:(function(){Notification.requestPermission().then(()=>{let e=0;console.log("find:",window.find("All checks have passed"));const n=setInterval(()=>{if(window.find("All checks have passed"))clearTimeout(n),new Notification("Github checks passed!");else{if(5===e){const e=document.createElement("label");e.innerHTML="All checks have passed",document.body.appendChild(e)}console.log("checks pending")}e+=1},1e3)})})();
美化版:
javascript: (function() {
Notification.requestPermission().then(() => {
let counter = 0;
console.log("find:",window.find("All checks have passed"));
const interval = setInterval(() => {
if (window.find("All checks have passed")){
clearTimeout(interval);
console.log("checks passed");
new Notification("Github checks passed!");
} else {
if (5 === counter) {
const el = document.createElement("label");
el.innerHTML = "All checks have passed";
document.body.appendChild(el);
}
console.log("checks pending");
}
counter += 1;
},1000)
})
})();
供您参考,此代码将在控制台中工作,它也会在您的控制台中填充消息。
希望它可以清除你的想法。
此代码 100% 有效,所以如果您仍然遇到问题,请告诉我,我一定会尽力帮助您。
,正如其他人所说,代码按预期工作。
我猜您在使用 setInterval
函数时遇到了问题。在Firefox上,SetInterval不会在选项卡上的焦点时运行(当您从书签选项卡执行书签时,您也会失去焦点)。
我假设您导航到导致计时器停止的其他选项卡。不幸的是,我认为没有一个简单的解决方案可以得到你想要的结果。
请参阅此处以供参考:SetInterval not running in Firefox when lost focus on tab/window