UNPKG

is-same-origin

Version:

Check if two URLs are same origin, for Node and the browser

54 lines (48 loc) 1.06 kB
/** @license is-same-origin v0.0.7 * Copyright (c) 2018-present, Qingrong Ke <keqingrong1992@gmail.com> (https://keqingrong.github.io/) * Released under the MIT license */ 'use strict'; const { URL } = require('url'); /** * Check if two URLs are same origin * @param {string} a - URL A * @param {string} b - URL B * * See * https://html.spec.whatwg.org/multipage/origin.html#same-origin * https://nodejs.org/dist/latest/docs/api/url.html */ function isSameOrigin(a, b) { var urlA = parseURL(a); var urlB = parseURL(b); if (!urlA || !urlB) { return false; } if (urlA.origin === urlB.origin) { return true; } if ( urlA.protocol === urlB.protocol && urlA.hostname === urlB.hostname && urlA.port === urlB.port ) { return true; } return false; } /** * Parse the URL string * @param {string} s - URL string * @returns {URL|null} */ function parseURL(s) { var url = null; try { url = new URL(s); } catch (error) { console.error(error); } return url; } module.exports = isSameOrigin;