【问题标题】:Chrome Extension Content script cannot listen an event until page is refreshedChrome 扩展内容脚本在页面刷新之前无法监听事件
【发布时间】:2014-05-29 05:44:44
【问题描述】:

我想创建一个扩展程序,以便在安装后立即将 html 注入每个打开的页面,而无需重新加载。

网页.html:

<html>
<head>
<meta charset="utf-8" />
<title>Extension</title>
<script>
  var go = function() {
    var event = document.createEvent('Event');
    event.initEvent('hello');
    document.dispatchEvent(event);
  };
</script>
</head>
<body>
<a href="javascript:go();">Click me</a> 
</body>
</html>

manifest.json:

{
  "name": "Chrome Extension Test",
  "version": "0.1",
  "description": "Test",
  "manifest_version": 2,

  "background" : { 
    "persistent": true,
    "scripts": ["background.js"]
  },  

  "permissions": ["http://*/*", "https://*/*"],
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content_script.js"]
  }]  
}

content_script.js:

(function() {
  document.addEventListener("hello", function(data) {
  chrome.runtime.sendMessage("test");
 });
})();

background.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  alert("message received");
  console.log("background message received");
});                 

如果扩展程序已经安装,它可以工作。但是如果在加载网页后安装扩展,内容脚本将无法接收从网页调度的事件,除非重新加载。

有没有办法在内容脚本中接收事件而无需重新加载?

【问题讨论】:

    标签: google-chrome-extension content-script


    【解决方案1】:

    有一个很长的canonical answer here。

    简而言之,如果您在初始化时需要内容脚本,您应该在后台脚本初始化时执行chrome.tabs.query({}, ...);,这将在所有带有chrome.tabs.executeScript({file: "content_script.js"}); 的选项卡中注入脚本。

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2013-01-26
      • 2014-10-27
      • 2016-11-29
      相关资源
      最近更新 更多