我尝试将消息从后台脚本发送到Chrome扩展程序中的内容脚本。但内容脚本似乎永远不会得到消息。
这是我的代码:
background.js
所以基本上我想每秒向活动标签的内容脚本发送一条消息。
'use strict';
var timeSpentToday = 0;
var timeSpentTotal = 0;
var today = (new Date()).getDate(); // today's day, to track day changing
var mainTimerId; // 1s timer that will update timeSpentToday every second
mainTimerId = setInterval(updateTime, 1000);
// function to be run every second
function updateTime() {
++timeSpentToday;
++timeSpentTotal;
console.log(timeSpentToday);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
if (tabs.length > 0) {
console.log(tabs)
chrome.tabs.sendMessage(tabs[0].id, {method: "sendTimeSpentToday", timeSpentToday: timeSpentToday}, function() {
console.log('message sent')
});
}
});
// check if we've changed day, and if it's the case, reset timeSpentToday to 0
if ((new Date()).getDate() != today) {
today = (new Date()).getDate();
timeSpentToday = 0;
}
}
content.js
console.log('Content script running.');
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request);
if (request.method == 'sendTimeSpentToday') {
var timeSpentToday = request.timeSpentToday;
console.log(timeSpentToday);
// update time label with hh:mm:ss format
var hours = parseInt( timeSpentToday / 3600 ) % 24;
var minutes = parseInt( timeSpentToday / 60 ) % 60;
var seconds = timeSpentToday % 60;
var hhmmss = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
document.getElementById('sf-timelabel').innerHTML = hhmmss;
}
}
内容脚本正在运行,我看到&#39; Content脚本正在运行&#39;在我的活动标签控制台中。后台脚本也正常运行,我看到timeSpentToday
每秒都会在扩展程序的控制台中被记录,并且“&#39;”消息已发送到&#39;消息也是。
请注意,我还在background.js
内记录了查询的标签页。我得到一个带有一个Tab对象的数组(活动选项卡):
Array[1]
0: Object
active: true
audible: false
height: 646
highlighted: true
id: 3635incognito: false
index: 2
mutedInfo: Object
pinned: false
selected: true
status: "complete"
width: 1332
windowId: 36
__proto__: Object
length: 1
__proto__: Array[0]
我只是不明白为什么sendMessage没有将消息发送到正确的内容脚本,或者为什么内容脚本没有收到消息。