如何在页面加载的同时弹出一个弹出页面时注入内容脚本? [英] How to Inject content script when page loads while having a popup page?

查看:219
本文介绍了如何在页面加载的同时弹出一个弹出页面时注入内容脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的代码使用内容脚本方法注入Google Chrome扩展。这只适用于我的清单没有弹出页面,而我的background.html有这样的内容:

Im trying to have my code to be injected using the content script method for google chrome extensions. This only works when my manifest does not have a Popup page and my background.html has this:

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
chrome.tabs.executeScript(null, { file: "content_script.js" });
});
});

如何在每次使用chrome加载新页面时触发此代码PoPup页面?因为到目前为止,它的工作方式是当我单击扩展的浏览器动作按钮时。

How can I have this code be triggered every time a new page has been loaded in chrome while having a PoPup page? because so far the only way that it works is when I click the browser action button of the extension.

另外在清单的内容脚本部分中,我包含了所有这些内容:

Also in my content script section of manifest I have included all this:

"content_scripts": [
{

"matches": ["http://jquery.com/*"],
"all_frames":true,
  "js": ["jquery.js","jquery-ui.min.js","content_script.js"],
   "run_at": "document_end"
}
],  


推荐答案

简短回答:使用 chrome.tabs.onUpdated.addListener 而不是 chrome.browserAction.onClicked.addListener ,以在每次更新页面时加载内容脚本。

Short answer: Use chrome.tabs.onUpdated.addListener instead of chrome.browserAction.onClicked.addListener from the background page to load the content script every time the page is updated.

很长的答案 CAN 实际上有一个内容脚本,当它们是一个弹出页面时,可以通过从清单包含内容脚本或使用背景页面的程序化注入来加载你的在

清单中:



Long answer: You CAN in fact have a content script be loaded when their is a popup page, either by including the content script from the manifest or using programmatic injection from the background page (as you suggested in your question).

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://myurl.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ],
  "permissions": [
     "http://myurl.com/*",
     "tabs"
  ],
  "background_page": "background.html",
  "browser_action": {
     "popup": "popup.html"
  }
  ...
}

确保matches属性与要加载内容脚本的页面的URL匹配。

Make sure the "matches" property matches the URL for the page you want to load the content script on.

您可以使用您在问题中建议的方式,在浏览器中插入内容脚本点击动作或,每次浏览器URL更新时都可以这样做:

You can use the way you suggested in your question, which will insert the content script when the browser action is clicked OR you could do it every time the browser URL is updated like so:

chrome.tabs.onUpdated.addListener(function() {
  chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
    chrome.tabs.executeScript(null, { file: "content_script.js" });
  });   
});

这篇关于如何在页面加载的同时弹出一个弹出页面时注入内容脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆