使用 JavaScript 检查同源 URL

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索如何使用 JavaScript 检查两个 URL 是否同源。我们将使用 URL.protocolURL.host 属性来比较 URL 的协议和主机,并确定它们是否属于同一来源。对于需要确保其 Web 应用程序安全性并防止跨站脚本攻击的 Web 开发人员来说,这是一项有用的技能。

检查两个 URL 是否同源

要检查两个 URL 是否同源:

  1. 打开终端/SSH 并输入 node 以开始练习编码。

  2. 使用 URL.protocolURL.host 检查两个 URL 是否具有相同的协议和主机。

const isSameOrigin = (origin, destination) =>
  origin.protocol === destination.protocol && origin.host === destination.host;
  1. 使用你要比较的 URL 创建两个 URL 对象。
const origin = new URL("https://www.30secondsofcode.org/about");
const destination = new URL("https://www.30secondsofcode.org/contact");
  1. 将两个 URL 对象作为参数调用 isSameOrigin 函数以获得布尔输出。
isSameOrigin(origin, destination); // true
  1. 你也可以使用其他 URL 测试该函数,以查看它们是否同源。
const other = new URL("https://developer.mozilla.org");
isSameOrigin(origin, other); // false

总结

恭喜你!你已经完成了同源 URL 实验。你可以在 LabEx 中练习更多实验来提升你的技能。