Chrome extension code no longer running when tab inactive?

我们两清 提交于 2019-12-24 00:54:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!