gpt4 book ai didi

javascript - 无法访问此站点 (ERR_CONNECTION_CLOSED) window.open 的 javascript 检测

转载 作者:可可西里 更新时间:2023-11-01 17:27:00 26 4
gpt4 key购买 nike

我有这段 javascript 代码在执行我的点击,它应该可以启用正确的点击跟踪。 clickDestinations都是不一样的,而且有很多(跨域)。

var response = window.open(clickDestination, randomName);
if (typeof response.focus === 'function') {
alert('tracking this click-out');
}

此实现的问题是 clickDestination 是由用户提供的,其中一些非常旧,因此无法保证正确设置了 http 或 https 协议(protocol)。

当使用错误的协议(protocol)调用 window.open 时,例如。在不支持 https 的网站上使用 https,我得到“无法访问此网站”页面 (ERR_CONNECTION_CLOSED)。但是我的跟踪器无论如何都会跟踪,因为 var response 是一个窗口对象。

在这种情况下,我如何检测错误而不进行跟踪,有什么想法吗?

最佳答案

如果 url 在同一个域中(同源策略适用于此处),第一个想法有效:

var w = window.open(url);

// if window opened successfully
if ( w ) {
w.onload = function() {
alert('tracking this click-out');
};
}

第二个想法:

window.open returns a reference to the newly created window. If the call failed, it will be null instead. Ref.

因此,如果连接失败是因为指定 URL 的服务器不支持 https 或将返回 http null,那么您可以使用此信息跳过您的跟踪代码。

示例(未测试):

var response = window.open(clickDestination, randomName);
// if destination cannot be open, skip tracking code
if(!response){
return;
}
if (typeof response.focus === 'function') {
alert('tracking this click-out');
}

关于javascript - 无法访问此站点 (ERR_CONNECTION_CLOSED) window.open 的 javascript 检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com