itzhar
itzhar

Reputation: 13031

Open URL in new safari tab - safari extention

generaly i ask exactly the same question as here:

Safari extension: Event for a completely new tab?

in this answer (case 3) he guide to listen click event inside inject.js.

can someone show this implementation?

Upvotes: 1

Views: 773

Answers (1)

Steven Schobert
Steven Schobert

Reputation: 4269

Here's an implementation I used for one of my previous extensions:

  1. Create a global.html file, and inside the Extension Builder, select that file under the Extension Global Page section:

Global Page Settings

  1. Source for global.html:

    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>My Extension</title>
      </head>
      <body>
        <script>
         function messageHandler(event) {
           var newTab = null;
           var url = null;
    
           if (event.name === "open_new_tab") {
             url = event.message;
             newTab = safari.application.activeBrowserWindow.openTab();
             newTab.url = url;
           }
         }
    
         safari.application.addEventListener("message", messageHandler, false);
        </script>
      </body>
    </html>
    
  2. Create an extension.js file, and add it to the Injected Extension Content -> End Scripts section:

end scripts

  1. Source for extension.js:

    (function() {
      // ... rest of you extension code 
      openNewTabWithUrl("http://google.com")
    
      function openNewTabWithUrl(url) {
        safari.self.tab.dispatchMessage("open_new_tab", url);
      }
    }());
    

This will send a message containing a URL from your extension.js to global.html, which will pick up the message and open the new tab.

Upvotes: 3

Related Questions