используйте событие "validate" в фоновом режиме для обнаружения переключений вкладок, например
var popupBackground = {
initialised : false,
activeTab : null,
numberOfTabs : null,
_init : function() {
var that = this;
// on browser initialise reset data
localStorage.clear();
// this initialises the popup dialogue
localStorage["popupOpened"] = false;
// register listeners for application messaging
safari.application.addEventListener("command", function(event){
that.handleCommand(event);
}, false);
safari.application.addEventListener("validate",function(event){
that.validateCommand(event);
}, false);
safari.application.addEventListener("message", function(event){
that.handleMessage(event);
}, false);
},
_getActiveTab : function(){
return safari.application.activeBrowserWindow.activeTab;
},
// commands are validated before being excecuted
validateCommand : function(aEvent) {
var that = this;
// all commands should have the identifier specified in Extension Builder
if (aEvent.command === "togglePopup") {
// check that there is an active tab
if (!aEvent.target.browserWindow.activeTab.url) {
aEvent.target.disabled = true;
} else {
aEvent.target.disabled = false;
}
}
// this is a hack for detecting tab switches, safari does not have a dedicated API like Chrome
if(this.activeTab !== null){
if(this.activeTab !== this._getActiveTab()){
$.each(safari.application.browserWindows, function(aIndex, aWindow) {
$.each(aWindow.tabs, function(aIndex, aTab) {
if(typeof aTab.page !== "undefined"){
// message all tabs about the focus switch event
if (aTab !== that._getActiveTab()) {
aTab.page.dispatchMessage("tabUnfocused");
// set the popup status (incase tab closed with open popup)
localStorage["popupOpened"] = false;
}else{
aTab.page.dispatchMessage("tabFocused");
}
}
});
});
}
}
// set the new active tab
this.activeTab = this._getActiveTab();
}
}