JavaScript 以编程方式强制关闭选项卡?

JavaScript force close a tab programmatically?

我运行遇到一些网站无法以编程方式关闭的问题:

window.close()

失败:

web/Stores.war/RAPIDStorefrontAssetStore/AJAXUserInterface/javascript/FDBrowse.js:301 Uncaught TypeError: Cannot read property 'style' of null
at close (web/Stores.war/RAPIDStorefrontAssetStore/AJAXUserInterface/javascript/FDBrowse.js:301)
at <anonymous>:1:8

违规网站是:https://www.1800flowers.com/about-us-employment-opportunities?utm_medium=direct&utm_source=1800flowerscom 尽管这也发生在其他人身上。

如何强制关闭?失败的关闭方法中的 运行ning 是什么?一些调查显示该文档未能在网站试图 运行 的脚本中找到某些文档元素,但我如何才能阻止它在关闭前 运行 宁任何东西?我试图将 on_X 方法设置为 null 没有成功...

您遇到的问题是该网站用其他功能覆盖了默认的 window.close 方法。

要解决此问题,您应该能够从母版页中 window.open() 返回的 Window 对象调用原始 Window.close 方法。

var popup = window.open('...');
popup.close(); // should be the original Window.close method

但是,如果出于某种原因,您绝对想从目标页面内部关闭此方法,那么您可以从 iframe 的 contentWindow,并在您损坏的页面上调用此方法。

function close(){
  console.log("It's bad to declare on the global scope");
}
console.log(window.close.toString());
window.close(); // our function

var iframe = document.createElement('iframe');
iframe.style.cssText = 'opacity:0;position:absolute';
iframe.src = 'about:blank';
iframe.onload = function() {
  console.log(iframe.contentWindow.close.toString());
  // you could call it like this
  iframe.contentWindow.close.call(window);
  // even if it will not work here because we didn't open the page programmatically
  document.body.removeChild(iframe);
};
document.body.appendChild(iframe);

这里是 a live plnkr 以更好地演示上面的代码。

以下语句 creates a new window 使用 window.open(),将 window.close() 重新绑定到 original window,随后 closes 两者。

(window.close = (w => w.close() || w.close)(window.open()))()

解释

1800 Flowers have overriden the global window.close 关闭 arbitrary element.

这在浏览器中 运行 console.log(window.close) 时很明显。

console.log(window.close) // ƒ close(){document.getElementById("overlay").style.display="none"}

您引用的 error 是由于 window.close()overridedocument.getElementById('overlay') 的缺失。

因此:"Cannot read property 'style' of null".

因此:要以编程方式关闭 1800 Flowerswindow.close() 必须重新启动(除非找到替代方法)。