use*_*788 7 javascript google-chrome popup google-chrome-extension
我有基于内容脚本的Chrome扩展程序.我通过内容脚本中的弹出窗口启动登录过程.
我使用下面的代码打开一个弹出窗口,然后等到它关闭.
但是,我从window.open方法中获得了"未定义" .有人知道为什么会这样吗?
loginwin是undefined在下面的代码虽然弹出窗口打开了罚款规定login_url.下面的代码是从我的内容脚本中调用的.
var loginWin = window.open(login_url, 'LoginWindow', "width=655,height=490");
console.log(loginWin);
// Check every 100 ms if the popup is closed.
var finishedInterval = setInterval(function() {
console.log('checking if loginWin closed');
if (loginWin.closed) {
clearInterval(finishedInterval);
console.log('popup is now closed');
Backbone.history.navigate('index', true);
}
}, 1000);
Run Code Online (Sandbox Code Playgroud)
注意:这个答案已经过时了.
window.open()在Chrome扩展程序中,始终返回null(当弹出窗口被阻止时)或window对象.以下信息仅适用于非常旧的(2012)版Chrome.
内容脚本无权访问页面的全局window对象.对于内容脚本,以下内容适用:
window变量没有指向页面的全局对象.相反,它指的是新的上下文,页面上的"层".页面的DOM完全可访问.#执行环境鉴于一份文件包括 <iframe id="frameName" src="http://domain/"></iframe>:
frames[0]并且frames['frameName'],(通常指的是包含全局window对象的框架)是undefined.var iframe = document.getElementById('frameName');
iframe.contentDocument返回document包含框架的对象,因为内容脚本可以访问页面的DOM.此属性null适用于同源策略.iframe.contentDocument.defaultView(指window与文档关联的对象)未定义.iframe.contentWindow 是不确定的.正如您所看到的,window.open()不会返回Window实例(也不会window.opener,等等).
在页面中注入代码,以便它在页面的上下文中运行.注意:如果您正在操作的页面可以信任,则仅使用此方法.要在注入的脚本和内容脚本之间进行通信,您可以使用:
var login_url = 'http://example.com/';
var event_name = 'robwuniq' + Math.random().toString(16); // Unique name
document.addEventListener(event_name, function localName() {
document.removeEventListener(event_name, localName); // Clean-up
// Your logic:
Backbone.history.navigate('index', true);
});
// Method 2b: Inject code which runs in the context of the page
var actualCode = '(' + function(login_url, event_name) {
var loginWin = window.open(login_url, 'LoginWindow', "width=655,height=490");
console.log(loginWin);
// Check every 100 ms if the popup is closed.
var finishedInterval = setInterval(function() {
console.log('checking if loginWin closed');
if (loginWin.closed) {
clearInterval(finishedInterval);
console.log('popup is now closed');
// Notify content script
var event = document.createEvent('Events');
event.initEvent(event_name, false, false);
document.dispatchEvent(event);
}
}, 1000);
} + ')(' + JSON.stringify(login_url+'') + ', "' + event_name + '")';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
Run Code Online (Sandbox Code Playgroud)使用后台页面启动窗口window.open().这将返回window具有可靠closed属性的对象.有关通信流程的更多详细信息,请参阅下一个要点.
chrome.windows.create打开一个窗口.在回调中,指定一个chrome.tabs.onRemoved和/或chrome.tabs.onUpdated事件.当触发这些事件侦听器时,它们应该自行删除,并使用sendResponse函数通知原始调用者(内容脚本)chrome.extension.onMessage.| 归档时间: |
|
| 查看次数: |
15898 次 |
| 最近记录: |