The Windows and Tabs API

The standard window.open() JavaScript method cannot be used to open a new tab and window from a global HTML file or an extension bar. Instead, the global file and extension bars have access to the SafariApplication, SafariBrowserWindow, and SafariBrowserTab classes, whose methods and properties allow you to work with windows and tabs.

In Safari 5.1 and later, there are additional events generated:

Navigation occurs whenever the user loads a new page in any manner—clicking a link in a tab or window, opening a bookmark, entering a URL in the address field, or typing a query in the web search field.

SafariApplication

There is one instance of the SafariApplication class: safari.application. The SafariApplication instance has a method for opening browser windows:

var myWin = safari.application.openBrowserWindow();

All open browser windows can be accessed as properties of the SafariApplication instance: safari.application.browserWindows is an array of all open windows, and safari.application.activeBrowserWindow is the currently active browser window.

SafariBrowserWindow

Each open browser window is an instance of the SafariBrowserWindow class, which has methods to activate windows, close them, and determine if a window is visible onscreen. The SafariBrowserWindow class also gives direct access to tabs.

A browser window is commonly accessed as a property of the Safari app instance:

safari.application.browserWindows[n]

or:

safari.application.activeBrowserWindow

SafariBrowserTab

The SafariBrowserTab class allows you to identify a tab’s parent browser window, get and set the URL associated with a tab, make a tab active, close a tab, and extract a data:// URL containing a snapshot image of what is rendered in the tab as a base-64 encoded PNG.

For example, this opens a window and returns the active tab:

var newTab = safari.application.openBrowserWindow().activeTab;

And this opens a new tab in the window containing the extension bar:

var newTab = safari.self.browserWindow.openTab();

Events

In Safari 5.1 and later, you can listen for and respond to the following window and tab events:

You can listen for these events on the application object from an extension bar or your global HTML page. You can also listen on a specific window or tab in the app.