Search code examples
htmlmacossafarionclicksafari-extension

How to open new tab with Button click in Safari with extension?


I am having issues opening a new tab in Safari browser with my extension. Using the Extension Builder I added bar.html:

<html>
<body>
  <form id="myForm">
    <input type="button" value="Button1" onclick="window.open('http://www.google.com')"/>
    <button onclick='window.open("https://www.google.com", "_blank");'>Button2</button>
  </form>
</body>
</html>

Neither of Button1 nor Button2 will open 'google.com' in a new tab, nor window. If I put them in a form as above, and click on Button2 it will open my bar.html in the current tab, and from there if I click either Button1 or Button2 it will open 'google.com' in my current tab.

enter image description here

enter image description here


Solution

  • I found this in Apple Dev library and it states "The standard window.open() method cannot be used to open a new tab and window from an extension bar. Instead, extension bars have access to the SafariApplication, SafariBrowserWindow, and SafariBrowserTab classes, which allow you to open, close, activate, and manipulate windows and tabs."

    So by using a function with safari.self.browserWindow.openTab I was able to open my link in a new tab.

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Safari Developer Reference</title>
            <button onclick="openInTab('http://www.google.com');">Click me</button>
            <script type="text/javascript">
                function openInTab(source){
                    var newTab=safari.self.browserWindow.openTab();
                    newTab.url=source;
                }
            </script>
        </head>
        <body style="color:#C02020;background:#C0C0C0;">
            <a href="javascript:openInTab('http://www.google.com');"> Google </a>
        </body>