UNPKG

is-same-origin

Version:

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

58 lines (52 loc) 1.35 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 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.isSameOrigin = factory()); }(this, (function () { 'use strict'; /** * 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; } return isSameOrigin; })));