Reputation: 53
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!
Upvotes: 4
Views: 2317
Reputation: 2829
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();
}
}
Upvotes: 4