How to open sidebar from content script click event

I have a content script that injects a grid of icons in the active tab. When a user clicks on an icon, I would like the sidebar to open.

I am aware that browser.sidebarAction.open(); can only be triggered by user actions. User actions include the following:

  • Clicking the extension’s browser action or page action.
  • Selecting a context menu item defined by the extension.
  • Activating a keyboard shortcut defined by the extension (this only treated as a user action from Firefox 63 onwards).
  • Clicking a button in a page bundled with the extension.

I tried the following code in the content script, but it looks like this API is not available to content scripts:

async function onGridClick(e) {
    e.preventDefault();
    e.stopPropagation();
    const result = await browser.storage.sync.get(null);
    if (result.options === 'openSidebar' {
        browser.sidebarAction.open();
    }
    if (logToConsole) console.log('Grid icon got clicked:' + e.type);
    const id = e.target.id;
    if (logToConsole) console.log('Search engine clicked:' + id);
    if (sameTab) {
        let nav = document.getElementById('icon-grid');
        nav.style.display = 'none';
        nav.removeEventListener('click', onGridClick);
        nav.removeEventListener('mouseleave', onLeave);
        nav = null;
    }
    const selection = window.getSelection();
    selection.addRange(range);
    sendMessage('doSearch', { id: id });
}

Sadly, you can’t :frowning:.

Make sure to vote for the bug:

The easiest workaround would be probably to tell user to press a keyboard shortcut :slight_smile:.

2 Likes