Javascript ONACTIVE每次都不工作

Javascript ONACTIVE每次都不工作,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我用以下数据创建了一个简单的chrome扩展,但由于某些原因,它不能一直工作,有时我需要单击扩展按钮,以便下次在当前选项卡中工作。 我不明白为什么。。当你点击一个标签并激活它时,它应该总是有效的(即使你创建了一个新的标签,它也会被激活,并且应该运行do something.js manifest.json { "manifest_version": 2, "name": "Test", "description": "Test", "version": "1", "bro

我用以下数据创建了一个简单的chrome扩展,但由于某些原因,它不能一直工作,有时我需要单击扩展按钮,以便下次在当前选项卡中工作。 我不明白为什么。。当你点击一个标签并激活它时,它应该总是有效的(即使你创建了一个新的标签,它也会被激活,并且应该运行
do something.js

manifest.json

{
  "manifest_version": 2,

  "name": "Test",
  "description": "Test",
  "version": "1",

  "browser_action": {
    "default_icon": "icon.png",
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": [
    "activeTab",
    "tabs"
  ]
}

background.js

chrome.tabs.onActiveChanged.addListener(function () {
  chrome.tabs.executeScript({
    file: 'do-something.js'
  });
});

do-something.js

function createNotification() {
  var notification = document.createElement('div');
  Object.assign(notification.style, {
    position: 'fixed',
    zIndex: 10000,
    textAlign: 'center',
    width: '100%',
    background: '#f5ae20',
    padding: '5px',
    top: 0,
    left: 0
  });
  notification.innerHTML = `Test`;
  document.body.appendChild(notification);
  setTimeout(function() {
    notification.remove();
  }, 4000);
  return notification;
}
createNotification();

为什么它一直不工作?

您的代码有问题。
做点什么。清单文件中应该提到js
,否则chrome将找不到任何东西,您可以将其作为内容脚本、背景脚本或web可访问资源

但是,如果您将其作为内容脚本,那么它将在每次加载页面时根据当前代码运行

这是我的方法 我将
do something.js
放在内容脚本中,并在后台发现活动选项卡已更改时,在后台js和内容脚本之间建立通信通道,然后向内容脚本发送消息并显示通知

从后台传递的消息

//listener for detecting tab change
chrome.tabs.onActiveChanged.addListener(function () {
  console.log("tab changed");
  //query about the active tab and get the tab id
  //if you add debug point here it will throw exception because debugger is the current active window , which doesnot have tab
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    //send the message to the content sctipt
    chrome.tabs.sendMessage(tabs[0].id, "showNotification", null);//here null is the callback
  });
});
内容脚本上的消息接收

chrome.runtime.onMessage.addListener(
  function (message, sender, sendResponse) {
    //you can receive  different type of message here
    if (message == "showNotification") {
      createNotification();
    }
  });
我已经为您添加了github回购协议,您可以在那里找到更多详细信息。

谢谢

为什么不使用“内容脚本”?“内容脚本”:[{“匹配项”:[“http://*/*”,“https://*/*”],“js”:[“content.js”]}],然后在content.js chrome.runtime.onMessage.addListener中添加一个侦听器,然后从后台发送消息