-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
43 lines (33 loc) · 1.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var assert = require('assert')
var safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/
var protocolLink = /^[\w-_]+:/
module.exports = href
function href (cb, root) {
assert.notEqual(typeof window, 'undefined', 'nanohref: expected window to exist')
root = root || window.document
assert.equal(typeof cb, 'function', 'nanohref: cb should be type function')
assert.equal(typeof root, 'object', 'nanohref: root should be type object')
window.addEventListener('click', function (e) {
if ((e.button && e.button !== 0) ||
e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ||
e.defaultPrevented) return
var anchor = (function traverse (node) {
if (!node || node === root) return
if (node.localName !== 'a' || node.href === undefined) {
return traverse(node.parentNode)
}
return node
})(e.target)
if (!anchor) return
if (window.location.protocol !== anchor.protocol ||
window.location.hostname !== anchor.hostname ||
window.location.port !== anchor.port ||
anchor.hasAttribute('data-nanohref-ignore') ||
anchor.hasAttribute('download') ||
(anchor.getAttribute('target') === '_blank' &&
safeExternalLink.test(anchor.getAttribute('rel'))) ||
protocolLink.test(anchor.getAttribute('href'))) return
e.preventDefault()
cb(anchor)
})
}