Skip to content

Instantly share code, notes, and snippets.

@iamspark1e
Created April 8, 2022 03:18
Show Gist options
  • Select an option

  • Save iamspark1e/e93bff929f9852402c25eda6863b9947 to your computer and use it in GitHub Desktop.

Select an option

Save iamspark1e/e93bff929f9852402c25eda6863b9947 to your computer and use it in GitHub Desktop.
Check any url is in safe parent domain without URL class. 检查任意URL是否在它的父级域下,不使用URL。
function isSafeParentDomain(url, safeDomains) {
try {
// Using polyfill for String.prototype.endsWith
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
var defaultSafeDomains = ["example.com", "www.abc.com"];
safeDomains = safeDomains || defaultSafeDomains;
// tricky method
var testHyperlink = document.createElement('a');
testHyperlink.href = url;
var flag = false;
for (var i = 0; i < safeDomains.length; i++) {
if (testHyperlink.hostname.endsWith(safeDomains[i])) {
flag = true;
break;
}
}
return flag;
} catch (e) {
console.log("safe parent domain check failed, error:")
console.log(e)
// skip notice if failed.
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment