Created
April 8, 2022 03:18
-
-
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。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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