Lac*_*rds 3 javascript jquery google-chrome-extension
我正在尝试将警报触发的消息从background.js 传递到loader.js。这是我的代码:
清单.json:
{
"update_url": "https://clients2.google.com/service/update2/crx",
"manifest_version": 2,
"name": "DubX",
"short_name": "DubX",
"author": "Al3366",
"description": "Automatically loads DubX on dubtrack.fm",
"homepage_url": "https://dubx.net/",
"version": "0",
"browser_action": {
"default_icon": "icons/48.png"
},
"permissions": ["background","alarms","tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["*://www.dubtrack.fm/*"],
"js": ["jquery.js","loader.js"],
"run_at": "document_end"
}],
"icons": {
"16": "icons/16.png",
"19": "icons/19.png",
"38": "icons/38.png",
"48": "icons/48.png",
"128": "icons/128.png"
}
}
Run Code Online (Sandbox Code Playgroud)
背景.js
chrome.alarms.create('hello',{delayInMinutes: 0.25});
chrome.alarms.onAlarm.addListener(function(alarm) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var content = {greeting: 'foo'};
chrome.tabs.sendMessage(tabs[0].id, content);
});
});
Run Code Online (Sandbox Code Playgroud)
加载器.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting === 'foo') {
hello();
};
}
);
$('body').prepend('<div class="cake" style=" z-index: 2147483647; color: white; position: fixed; bottom: 54px; left: 27px; background: #222; padding: 13px; -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75); box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.75); border-radius: 5px;">Waiting for Dubtrack...</div>');
function hello() {
$.getScript('https://rawgit.com/sinfulBA/DubX-Script/master/beta.js');
$('.cake').remove();
};
Run Code Online (Sandbox Code Playgroud)
它不断地触发 hello(); 每 4 秒运行一次。我不知道我做错了什么。预先感谢您的回复。
您正在使用事件页面(非持久后台页面),该页面将在大约 5 秒不活动后卸载。然后浏览器中的某些活动会导致后台页面重新初始化并设置新的警报。因此,每 5 秒新警报就会触发处理程序,发送一条消息,从而调用内容脚本hello()。
解决方案 1:在调用之前检查某些条件chrome.alarms.create。
例如,如果真正的目标是在浏览器启动后触发一次警报,请使用onStartup 事件并使用 key 设置警报时间when:
chrome.runtime.onStartup.addListener(function() {
chrome.alarms.create('hello', {when: Date.now() + 60*1000});
});
Run Code Online (Sandbox Code Playgroud)
请注意,在已发布的扩展中,即使您指定较小的值(例如 15 秒 (15*1000)),下一个警报与上次触发的警报之间的间隔也至少为 1 分钟。
解决方案 2(不好的方案):使用 . 使后台页面持久化"persistent": true。这很糟糕,因为持久的后台页面会占用内存。然而,正如 Xan 的回答中所解释的,如果您实际上需要每 15 秒触发一次警报,那么这是一个完美的选择。