Chrome扩展程序:加载时自动启动内容脚本

时间:2017-10-09 14:11:42

标签: javascript google-chrome-extension polling

搜索过SO,谷歌Chrome开发者文档和其他网站...我仍然无法让我的内容脚本自动启动。基本上,我需要内容脚本每隔x秒轮询一次div innerHtml,并向background.js脚本发送一条消息以供进一步处理。看起来很简单,但即使指定了“run_at”:“document_end”,它也永远不会启动。我怀疑它是微不足道的,所以我只是在寻找其他眼睛来指出我正确的方向。此外,它需要在没有用户交互的情况下运行。

这是我的manifest.json文件:

{
  "name": "My Extension Name",
  "description": "Extension description",
  "version": "1.0",
  "background": {
    "scripts": ["bg.js"]
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "content_scripts": [{
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"],
      "run_at": "document_start",
    }],
  "manifest_version": 2
}

我的content.js文件:

var pollInterval = 30000;
var timerId;

function startPoller() {
  var elementOfInterest = document.getElementById('id_of_interest');
  var content = elementOfInterest.innerHtml;
  chrome.runtime.sendMessage({payload: content});
  timerId = window.setTimeout(startPoller, pollInterval);
}

document.addEventListener('DOMContentLoaded', function () {
  startPoller();
});

和bg.js文件:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(JSON.stringify(request));
  }
);

因此它非常无趣。帮助赞赏。

1 个答案:

答案 0 :(得分:0)

工作代码如下:

manifest.json文件:

{
  "name": "My Extension Name",
  "description": "Extension description",
  "version": "1.0",
  "background": {
    "scripts": ["bg.js"]
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "content_scripts": [{
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"],
      "run_at": "document_start",
    }],
  "manifest_version": 2
}

content.js文件:

var pollInterval = 5000;
var timerId;

function startPoller() {
  try {
    console.log('startPoller called');
    var elementOfInterest = document.getElementById('nav_home');
    if (elementOfInterest !== undefined && elementOfInterest !== null) {
      var content = elementOfInterest.innerHTML;
      chrome.runtime.sendMessage({payload: content});
    }
  } catch (error) {
    console.log(error);
  }
  timerId = window.setTimeout(startPoller, pollInterval);
}

window.addEventListener('DOMContentLoaded', function () {
  console.log('window.addEventListener');
  startPoller();
});

bg.js文件:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(JSON.stringify(request));
  }
);

感谢您的眼球,伙计们