Question

I have this javascript code:

function handleCommand (event) {
    if (event.command === 'send') {
        sendingLink(event.target.browserWindow.activeTab.url);
    } else if (event.command === 'sendMenu') {
        sendingLink(safari.application.activeBrowserWindow.activeTab.url);
    }
};

I want to be able to make an "if" statement where I: 1) grab the id "leurl" if the link is "https://maps.google.com/, and 2) if it's not a Google Map link, then grab the link from the address bar. I got the second part, but I don't know how to do the first one. I know how to do it when making a Google Chrome extension though (document.getElementById('link');).

How would I be able to accomplish this? Any help is appreciated. Thank you in advance.

Please forgive me as I am not too familiar at making Safari extensions.

Was it helpful?

Solution

If I understand correctly, you want to get some information contained on the current page into your global page. Unfortunately using document.getElementById('link'); won't work directly, as the global page doesn't have access to the content of web pages (for security reasons, I think).

You will have to use an injected script, and messaging to send the information to the global page. For example, you might do the following:

global.js

const app = safari.application;
app.addEventListener('message', handleMessage, false);

function sendingLink(link) {
    app.activeBrowserWindow.activeTab.page.dispatchMessage('getLink');
}

function handleMessage(msg) {
    if (msg.name === 'returnLink') {
        alert(msg.message);
    }
}

injected.js

safari.self.addEventListener('message', handleMessage, false);

function handleMessage(msg) {
    if (msg.name === 'getLink') {
        // Trigger share button. Maybe:
        // document.getElementById('link').click();
        var link = document.getElementById('leurl').value;
        safari.self.tab.dispatchMessage('returnLink', link);
    }
}

Then make sure these are set as the global page and an injected script respectively, in the Safari Extension Builder.

The Apple Safari Extensions Development Guide is a great resource for things like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top