问题
I created a very simple Chrome extension for personal use that sent me a browser notification if a DOM element changed in a tab that had a specific site open and switch that tab to be the active one.
It would work if the tab was not active and open (intended/wanted behavior), but recently the notification no longer sends unless the tab is active. I haven't changed any of the code, so not sure if a recent Chrome update changed the behavior of the API.
Here's my code:
manifest.json
{
"name": "New Element Notifier",
"version": "1.0",
"description": "Creates notification if new element exists.",
"permissions": [
"notifications"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://*.website.com/*"],
"js": ["jquery.min.js", "website.js"],
"run_at": "document_end"
}
],
"web_accessible_resources": [
"*.wav"
],
"manifest_version": 2
}
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "new-element") {
chrome.tabs.update(sender.tab.id, {active: true});
var options = {
type: "basic",
title: "New Element",
message: "A new element exists!",
iconUrl: "icon.png"
}
chrome.notifications.create(options);
sendResponse({confirm: "tab changed"});
}
});
website.js
var elementContainer = document.querySelectorAll(".items-container")[0];
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
chrome.runtime.sendMessage({type: 'new-element'}, function(response) {
console.log(response.confirm);
});
}
});
});
observer.observe(elementContainer, {characterData: true, childList: true, subtree: true});
Not sure what happened as it was working fine for a long time. Any help with this would be appreciated!
来源:https://stackoverflow.com/questions/55498281/chrome-extension-code-no-longer-running-when-tab-inactive