javascript - window.close 不适用于 Twitter 网站
问题描述
我有一个打开 Twitter URL (window.open()) 的代码,但我认为 Twitter 正在清除/擦除我的窗口引用,这就是为什么我不能再控制我的窗口或使用 window.close() 关闭它的原因。解决方法是什么?
我试图 console.log 这个,如果网站加载,窗口总是空的。这是代码:
var windows = {};
function OpenWindow(id, url, title, w, h, l) {
$.each(windows, function(index, value) {
if (windows[index].closed) {
$('#' + index + '').css("background-color", "");
}
});
$('#' + id + '').css("background-color", "#F2F5F7");
// Fixes dual-screen position Most browsers Firefox
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + l);
windows[id] = newWindow;
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
}
//When I tried to close this window using this function
//It is no longer working and the window is null
function closeWindow(name) {
var window = windows[name];
if (window) {
window.close();
delete windows[name];
}
}
解决方案
这是因为twitter.com使用“同源”cross-origin-opener-policy
标头。
由于您的页面不是来自同一来源,因此会创建一个新的顶级浏览上下文,并且您的浏览上下文将始终将此新浏览上下文视为已关闭并且无法关闭它。
推荐阅读
- typescript - 如何使 Visual Studio Code 停止显示 node_modules 文件夹的打字稿错误?
- sql - 将多个文件夹中的多个 PDF 导入 SQL 表。
- c - 旧类型的新类型:我可以得到一个宏来为我做我的工作吗?
- ruby-on-rails - 反应路由器和铁路路线
- php - Laravel 迁移,在 hasColumn 方法上失败
- amazon-web-services - 你可以使用 Perl Paws 获得预签名的 URL 吗?
- julia - 获取Julia中p个最大特征值对应的特征向量
- ibm-cloud - 从 SL API 获取 iSCSI 设备的磁盘标识符
- r - R - dplyr::case_when 评估不正确
- microsoft-graph-api - Teams Messages Beta Endpoint - 不支持使用 MSGraph 应用程序权限调用此 API