首页 > 解决方案 > 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];
  }
}

标签: javascriptjquery

解决方案


这是因为twitter.com使用“同源”cross-origin-opener-policy标头。

由于您的页面不是来自同一来源,因此会创建一个新的顶级浏览上下文,并且您的浏览上下文将始终将此新浏览上下文视为已关闭并且无法关闭它。


推荐阅读