Last active
August 27, 2024 11:01
-
-
Save ArtemAvramenko/3b3fdb0ece3435b540074c6f3950d346 to your computer and use it in GitHub Desktop.
Copy URL UserScript
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
// ==UserScript== | |
// @include * | |
// @noframes | |
// @grant unsafeWindow | |
// @grant GM_registerMenuCommand | |
// @grant GM_setClipboard | |
// ==/UserScript== | |
GM_registerMenuCommand('Copy URL', () => { | |
let url = window.location.href; | |
let selectionBound; | |
let selection = document.getSelection(); | |
for(let node = !selection.isCollapsed && selection.anchorNode; node; node = node.parentNode) { | |
if (node.getBoundingClientRect) { | |
selectionBound = node.getBoundingClientRect(); | |
break; | |
} | |
} | |
if (selectionBound) { | |
var tags = []; | |
for (let element of document.querySelectorAll('[id]')) { | |
if (element.id) { | |
let bound = element.getBoundingClientRect(); | |
if (bound.left < selectionBound.right && bound.right > selectionBound.left) { | |
let diff = selectionBound.top - bound.top; | |
if (diff >= 0 && diff < 1000) { | |
tags.push({id: element.id, diff}); | |
} | |
} | |
} | |
} | |
if (tags.length) { | |
tags.sort((a, b) => (a.diff - b.diff) || (a.id.length - b.id.length)); | |
url = url.split('#')[0] + '#' + tags[0].id; | |
} | |
} | |
url = decodeURIComponent(url).replace(/%20/g,'%2520') | |
GM_setClipboard(url); | |
}, 'c'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment