javascriptsafarisafari-extensionsafari-app-extension

Open new tab with JavaScript in Safari 12 [Safari App Extension]


I have this extension where I want to open a new tab in the JavaScript part of the extension. Before migrating it to a Safari App Extension I could just do

window.open(url, "_blank");

But when I run this in Safari 12 as an App Extension it adds the current link to the Reading List (?!).

When I run the code above in the console it opens a new tab of the url, but I have to enable popups in the Safari Preferences. I can't find anything in Apple's very poor documentation.

Is this even possible on "client side", or do I have to handle this in the Swift code?


Solution

  • If you'd like to open a new tab using Safari App Extensions, you'd need to do that in native code.

    You can achieve this by obtaining the active window, and then calling the openTab() method on that window.

    Below is a snippet that achieves this:

    let myUrl = URL(string: "https://google.com")
    
    
    // This grabs the active window.
    SFSafariApplication.getActiveWindow { (activeWindow) in
    
            // Request a new tab on the active window, with the URL we want.
            activeWindow?.openTab(with: myUrl, makeActiveIfPossible: true, completionHandler: {_ in
                // Perform some action here after the page loads if you'd like.
            })
        }