简体   繁体   English

Chrome扩展程序可加载页面并注入代码

[英]Chrome extension to load a page and inject code

I am trying to create a simple extension which will load a given page and inject code once the page has loaded. 我正在尝试创建一个简单的扩展程序,该扩展程序将加载给定的页面并在页面加载后注入代码。

I came up with the following, am I doing this the right way? 我提出了以下建议,我这样做正确吗?

background.js background.js

    chrome.tabs.getCurrent(function (tab) {
      chrome.tabs.update(tab.id, {url: "http://www.EXAMPLE.COM"});
    });

    chrome.tabs.onUpdated.addListener(function(tabId , info) {
        if (info.status == "complete") {
                 chrome.tabs.executeScript(null, {file: "content_script.js"});
        }
    });

Quoting chrome.tabs documentation for chrome.tabs.getCurrent : chrome.tabs文档引用为chrome.tabs.getCurrent

Gets the tab that this script call is being made from. 获取进行此脚本调用的选项卡。 May be undefined if called from a non-tab context ( for example: a background page or popup view). 如果是从非制表符上下文调用的,则可能是未定义的( 例如:背景页面或弹出视图)。

To grab the currently active tab, you should instead use chrome.tabs.query : 要获取当前处于活动状态的标签,您应该改用chrome.tabs.query

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
  // Do something with tabs[0]
});

Alternatively, if you're reacting to user input, like a click on the browser action, you're already supplied the current tab: 另外,如果您对用户输入做出反应(例如单击浏览器操作),则已经提供了当前标签:

chrome.browserAction.onClicked.addListener(function(tab){
  // "tab" is the current active tab
});

Instead of grabbing an already-open tab, you can simply create a new one (depends on what you're trying to achieve, of course): 您可以简单地创建一个新标签(而不是获取已经打开的标签)(当然,这取决于您要实现的目标):

chrome.tabs.create({url: "http://www.EXAMPLE.COM"});

Your listener will try to inject the content script into the current tab (you used null ) whenever any tab finishes loading, not just the one you created. 每当任何标签(而不只是您创建的标签)加载完成时,您的侦听器都会尝试将内容脚本注入当前标签(您使用null )。 It's safer to do so from create / update callbacks, ie create / update回调中这样做比较安全,即

chrome.tabs.update(tab.id, {url: "http://www.EXAMPLE.COM"}, function(tab){
  chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
});

Note: you don't have to worry that the page did not finish loading at this point. 注意:您不必担心页面此时尚未完成加载。 executeScript obeys the run_at parameter , which defaults to "sometime after DOM is loaded". executeScript遵循run_at参数 ,该参数默认为“ DOM加载后的某个时间”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM