Copy link address (Chrome or Safari) (Newbie alert)

Hi @Luoto,

Thanks for clarifying, that was easier to understand.

I presume the displayed text for a given link could be of any length and word count ? The example you gave using "GET" seems very precise, but I'm going to proceed as if you intended a more generalised example.

In order to use a link's anchor text (the text displayed to a user in the form of a hyperlink) to retrieve its target (the URL given by the value of the href attribute), you need to use a bit of JavaScript.

Therefore, firstly, you want to make sure that the relevant JavaScript settings permit us to run code within a browser tab. For Google Chrome, I believe the content settings control this: chrome://settings/content. In Safari, you can enable the Develop menu in the application preferences under the Advanced pane, then make sure Allow JavaScript From Apple Events is ticked.

One example piece of JavaScript code that will get you a hyperlink's target from its anchor text is:

var anchorText = 'Copy link address';
Array.from(document.links, 
           e=>(e.textContent
                .toLowerCase()
                .indexOf(anchorText.toLowerCase())!==-1
               &&
               e.href)
          ).filter(e=>(e!==false));

This performs a case-insensitive, fuzzy search, which will match any anchor text that contains the given anchorText.

To perform an exact match, this code will achieve that:

var anchorText = 'Copy link address (Chrome or Safari) (Newbie alert)';
Array.from(document.links, 
           e=>(e.textContent
                .trim()==anchorText
               &&
               e.href)
          ).filter(e=>(e!==false));

To demonstrate how this is implemented within a KM macro, I've created this one:


Find Links Using Anchor Text.kmmacros (27.7 KB)

Summary

A Typed String-triggered macro, triggered by entering text of the form A[%anchorText%] in any text box, where:

  • A: is a literal uppercase or lowercase "A", signifying that the anchor text to be supplied is to be matched exactly (uppercase) or fuzzily (lowercase).
  • %anchorText%: is the text supplied against which hyperlinks are to be matched by their text content, to within the allowances provided for by A or a.

The trigger text is removed and replaced with the matching URL(s), which are also stored on the clipboard.

e.g.

A[Find Links Using Anchor Text.kmmacros]https://forum.keyboardmaestro.com/uploads/default/original/3X/5/0/5038c1d0c9e8e0396b8a7ba5300f6cf149f7a7f6.kmmacros

A[Find Links Using](empty string) (i.e. no matches)

a[Find Links]https://forum.keyboardmaestro.com/uploads/default/original/3X/5/0/5038c1d0c9e8e0396b8a7ba5300f6cf149f7a7f6.kmmacros

A[Luoto]https://forum.keyboardmaestro.com/u/Luoto, https://forum.keyboardmaestro.com/u/Luoto, https://forum.keyboardmaestro.com/t/copy-link-address-chrome-or-safari-newbie-alert/10177/3

2 Likes