【问题标题】:How can I manipulate a new window in a Chrome Extension?如何在 Chrome 扩展程序中操作新窗口?
【发布时间】:2012-12-26 18:05:12
【问题描述】:

我正在编写一个 chrome 扩展程序,以允许用户从单个页面登录到社交媒体网站。我能够创建一个新的隐身窗口,但无法操作我创建的窗口内的任何内容。我想为新窗口创建一个 onload 函数来执行 jquery。感谢您为我指明了正确的方向!

【问题讨论】:

  • 您是否尝试过通过回调选项卡 create/update() 进行脚本注入?
  • 我没有,但我不知道从哪里开始。有什么好的资源可以指点我吗?
  • 如果你想操作隐身模式,你必须让用户在设置中勾选你的扩展下的“允许隐身模式”
  • @ChrisJenkins:检查我的答案,如果您有任何问题,请告诉我。

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

请参阅以下演示,了解如何操作创建的新隐身window 并将一些 jquery 注入其中。

References

manifest file

这用于绑定权限并将后台页面注册到扩展程序。确保它具有所需的所有权限。

{
"name":"Hanlder for Incognito window",
"description":"http://stackoverflow.com/questions/14044338",
"version":"1",
"manifest_version":2,
"background":{
    "scripts":["background.js"]
},
"permissions":["tabs","http://www.google.co.in/"]
}

background.js

从后台页面将 jquery 注入新的隐身窗口。

var _tabId_To_Look_For;

// Create a new incognito Window with some arbitary URL and give it focus
chrome.windows.create({
    "url": "http://www.google.co.in/",
    "focused": true,
    "incognito": true
}, function (window) {
    // Trace tab id which is created with this query 
    _tabId_To_Look_For = window.tabs[0].id
});

// Add an event Listener for new tab created
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    // Inject script into chosen tab after it is loaded completely
    if (tabId == _tabId_To_Look_For && changeInfo.status == "complete") {
        // Inject Jquery and in current tab
        chrome.tabs.executeScript(tabId, {
            "file": "jquery.js"
        }, function () {
            // I am in call back
            console.log("Injected some jquery ");
        });
    }
});

确保您已启用隐身访问。

Output

您将看到一个注入了 jquery 的新窗口。

【讨论】:

  • 今天我刚刚学会了如何使用file 选项将脚本注入标签页,谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 2018-04-29
  • 1970-01-01
相关资源
最近更新 更多