9

I'm trying to build a Safari Extension where when a user hits Command+B it will show the popover. Using the code below it works but always shows the popover on a different window not the current window/tab. I would like it to display the popover on the current window instead of switching to a different window and opening the popover there. It works perfectly if there is only one Safari window open but starts to have problems when multiple windows are open.

Any ideas?

Global Page File:

<script>
    safari.application.addEventListener('message', function (e) {
        if (e.name == 'Show Popover') {
            safari.extension.toolbarItems[0].showPopover();
        }
    }, false);
</script>

Injected Content:

document.addEventListener("keydown", keydown);

function keydown(event) {
    if ( event.metaKey && event.keyCode == 66) {
      event.preventDefault();
      safari.self.tab.dispatchMessage('Show Popover', {});
    }
}
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

1 Answers1

6

This is because you are manually selecting the first toolbarItem here;

safari.extension.toolbarItems[0].showPopover(); 

You need to determine which toolbarItem the popover needs to appear on;

Something like this;

var toolBarID = 'my_id';
var activeItem = safari.extension.toolbarItems.filter(function (button) {
    return button.identifier == toolBarID && button.browserWindow == safari.application.activeBrowserWindow;
})[0];

You then use this object for the showPopover function;

activeItem.showPopover();

Hope this helps

JayIsTooCommon
  • 1,714
  • 2
  • 20
  • 30
  • Great that looks like it worked!! Thank you very much for your help. One note is I did have to change `toolbarItemId` to my actual toolbarItemId. Would be nice if you could edit your answer to mention that just for future reference and for other users. Thanks again. – Charlie Fish Aug 18 '16 at 19:09
  • @CharlieFish No problem, and oops my bad - updated :) – JayIsTooCommon Aug 18 '16 at 19:40
  • Thanks again. Just so you are aware I will be awarding the bounty at the end of the 7 day period. :) – Charlie Fish Aug 18 '16 at 19:43