Reputation: 889
I would like to hover my mouse on a URL and copy the URL with CTRL+Alt+C. This topic pretty much describes 99% of what I'm trying to do: https://www.autohotkey.com/board/topic/111762-mouse-hover-copy-link/?p=662644
I've taken the userscript and modified it slightly, so that it gives me the URL after the "href" part. By the way, I'm not at all proficient with Javascript, I've simply played around with it and was lucky to get it working. Here's what I have:
This works great, but this copies the URL everytime I hover my mouse on a link. I don't want this, as it just adds a bunch of URLs to my clipboard.
At the bottom of that post, there's a Autohotkey component. It gets the tab title, rather than the URL.
How can I modify both the userscript and the Autohotkey to do what I want?
As a secondary question - I would like to create an additional userscript using the Javascript above as a reference. This new userscript will take the URL that my mouse is hovering on, change it so that it is prefixed with word:ofe|u| and pastes that into the URL bar when I click on the link while holding the Alt key. So basically:
UPDATE:
I've managed to get something going, not sure how I did it but I just played around with the codes I found on Google. Again, I do not know anything about Javascript.
// ...
This works well, but if you do single press of CTRL+C, it just keeps copying URLs to the clipboard whenever you hover your mouse on a link. I want it to only start copying a URL to the clipboard everytime I press CTRL+C.
Upvotes: 0
Views: 2766
Reputation: 6597
AutoHotkey won't help much here, as it can't access the URL directly. Thankfully, you can use the new JavaScript Clipboard API. It only works in secure contexts (AKA HTTPS) and the page needs to be in focus. Doing this using a browser extension would be perferred, since it can workaround those restrictions.
Try it, but first click on a blank area in the preview window to focus it.
// Userscript
"use strict";
window.addEventListener("load", () => {
const evOpts = {capture: true, passive: true};
let hoveredLink = null;
for (let link of document.getElementsByTagName("a")) {
link.addEventListener("mouseenter", () => {
hoveredLink = link;
}, evOpts);
link.addEventListener("mouseleave", () => {
hoveredLink = null;
}, evOpts);
}
window.addEventListener("keydown", (ev) => {
if (hoveredLink && ev.ctrlKey && ev.altKey && ev.code === "KeyC") // Ctrl+Alt+C
// Copy *absolute* URL to the clipboard
navigator.clipboard.writeText(new URL(hoveredLink.href, location.href)).then(()=>{
console.log("URL copied to clipboard!");
}, (err)=>{
console.error("Error copying URL to clipboard: ", err);
});
}, evOpts);
});
<a href="//google.com">Google</a> <a href="https://youtube.com/">Youtube</a>
Upvotes: 2