4

I am creating a safari extension. how do I manually set the new tab/window to a URL of my choosing? I used some of logic from this post to make sure I am only taking over user created tabs/windows Safari extension: Event for a completely new tab?

I set up my new tab event listener:

safari.application.addEventListener("open", handleOpen, true);

Using this to handle the open tab/window:

function handleOpen(e) {
    if (e.target instanceof SafariBrowserTab) {
        e.target.addEventListener('beforeNavigate', handleBeforeNavigate, false);
        setTimeout(function () {
            e.target.removeEventListener('beforeNavigate', handleBeforeNavigate, false);
            takeOverTab();
        }, 50);
    }
}

function handleBeforeNavigate(e) {
    e.target.removeEventListener('beforeNavigate', handleBeforeNavigate, false);
    if (e.url === null) {
        takeOverTab();
    }
}

function takeOverTab() {
window.location.href = "http://www.yahoo.com";
}

I am able to alert when a new tab/window is opened, but I cant for the life of my figure out how to actually browse to the url. I tried window.location.href but that doesn't seem to do anything, I still get the "top sites" page when I open a new tab.

Thanks in advance!

Community
  • 1
  • 1
James
  • 53
  • 5

1 Answers1

4

Change your takeOverTab function as follows:

function takeOverTab(tab) {
    tab.url = "http://www.yahoo.com";
}

And modify the function call to include a reference to the tab:

takeOverTab(e.target);

Also, in your beforeNavigate handler, you should add e.preventDefault() to prevent the tab from loading whatever it was going to load:

function handleBeforeNavigate(e) {
    e.target.removeEventListener('beforeNavigate', handleBeforeNavigate, false);
    if (e.url === null) {
        e.preventDefault();
        takeOverTab();
    }
}
chulster
  • 2,809
  • 15
  • 14
  • Just so no one gets confused here, even though @canisbos' (helpful) answer does work, it does interchange `tab` with `e` which is what is used in the rest of the example. So if you want to stay in line with the example, use `function takeOverTab(e) {e.url = "http://www.yahoo.com";}` – Tyler Hayes Oct 19 '14 at 20:57
  • No no no, Tyler, you do not do that. e is for the entire event. tab is e.target, which is the tab. It would be just asking for trouble, to use the same variable name for the variable.property pointer. – Kaz Vorpal Sep 28 '16 at 20:39