Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active August 27, 2024 11:01
Show Gist options
  • Save ArtemAvramenko/3b3fdb0ece3435b540074c6f3950d346 to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/3b3fdb0ece3435b540074c6f3950d346 to your computer and use it in GitHub Desktop.
Copy URL UserScript
// ==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