📌  相关文章
📜  javascript 如何知道网站是否安全 - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:32.540000             🧑  作者: Mango

Javascript 如何知道网站是否安全

在 Javascript 中,我们可以通过一些 API 来判断当前网站是否安全。以下是几种常用的方法:

1. window.location.protocol

通过检查当前页面 URL 的协议是否为 HTTPS,我们可以知道当前页面是否是通过加密协议传输数据的,进而判断当前网站是否安全。

if (window.location.protocol === 'https:') {
  console.log('This website is secure.');
} else {
  console.log('This website is not secure.');
}
2. document.location.protocol

与上面的 API 类似,也是获取当前页面 URL 的协议,用法相同。

if (document.location.protocol === 'https:') {
  console.log('This website is secure.');
} else {
  console.log('This website is not secure.');
}
3. window.isSecureContext

在安全上下文中,脚本只能通过安全连接与非安全连接进行网络请求,因此我们可以通过检查当前页面是否处于安全上下文中,来判断当前网站是否安全。

if (window.isSecureContext) {
  console.log('This website is secure.');
} else {
  console.log('This website is not secure.');
}
4. document.referrer

通过检查当前页面的来源,我们可以判断当前页面是否来自于安全站点。如果当前页面是从一个非安全站点跳转而来,那么当前页面可能不是安全的。

if (document.referrer.startsWith('https://')) {
  console.log('This website is secure.');
} else {
  console.log('This website is not secure.');
}

除了上述方法外,我们还可以使用一些第三方库来帮助我们确定当前网站是否安全,例如 Google 的 Safe Browsing API、Mozilla 的 Observatory API 等。在实际应用中,我们可以结合多种方法来判断当前网站是否安全,以提高准确性和可靠性。

参考链接:MDN Web Docs