How to get the URL of a right-clicked link sent to an automator action

linksservices

I'd like to create a service to open a link in Chrome. I already have this service installed: Safari Extension for right click menu: Open in Google Chrome?

This works if I right-click on selected text that is a URL. But it doesn't work if I right-click a link whose title is not a URL. For example, I'd like to right click a thread title at http://meh.com/forum and have have a command under Services to open that link in Chrome. The service referenced above doesn't show up in the Services contextual menu. Safari has a "Copy Link" menu item in the contextual menu. Is there a way to trigger that command from Automator or AppleScript?

Best Answer

Try this code on Automator action "Run Javascript".

for Chrome

function run(input, parameters) {

    var app = Application("Google Chrome");
    app.includeStandardAdditions = true;

    var url = app.windows[0].activeTab.execute({
        javascript: 'window.getSelection().anchorNode.parentNode.href'
    });

    return url;
}

for Safari

function run(input, parameters) {

    var app = Application("Safari");
    app.includeStandardAdditions = true;

    var url = app.doJavaScript('window.getSelection().anchorNode.parentNode.href',{
        in: app.windows[0].currentTab
    });

    return url;
}

For example enter image description here

Right click on the link and select "Copy link to clipboard" service, then you can get the URL.