| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- /**
- * 安全打开外链:仅允许 http/https,并可按域名白名单限制
- */
- const DEFAULT_HOST_WHITELIST = [
- 'cdwjyyh.com',
- 'jnmyunl.com',
- 'obs.jnmyunl.com',
- 'cos.his.cdwjyyh.com'
- ]
- function isWhitelistedHost(hostname, whitelist) {
- if (!hostname) return false
- const host = hostname.toLowerCase()
- return whitelist.some(domain => host === domain || host.endsWith('.' + domain))
- }
- /**
- * @param {string} url
- * @param {object} [options]
- * @param {string[]} [options.hostWhitelist]
- * @returns {boolean}
- */
- export function isSafeHttpUrl(url, options = {}) {
- if (!url || typeof url !== 'string') return false
- const trimmed = url.trim()
- try {
- const u = new URL(trimmed)
- if (u.protocol !== 'http:' && u.protocol !== 'https:') return false
- if (u.username || u.password) return false
- const whitelist = options.hostWhitelist || DEFAULT_HOST_WHITELIST
- if (whitelist.length > 0 && !isWhitelistedHost(u.hostname, whitelist)) {
- return false
- }
- return true
- } catch (e) {
- return false
- }
- }
- /**
- * 安全 window.open
- */
- export function safeOpen(url, target = '_blank') {
- if (!isSafeHttpUrl(url)) {
- console.warn('拒绝打开不安全链接:', url)
- return null
- }
- return window.open(url, target, 'noopener,noreferrer')
- }
- export default {
- isSafeHttpUrl,
- safeOpen
- }
|