Last active
April 25, 2023 20:44
-
-
Save aghwotu/5fbbc2fd87a1ef5fce6db26b0b23d18a to your computer and use it in GitHub Desktop.
Use different popups in your Chrome extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This is a workaround for the `chrome.action.openPopup()` which is not (yet) available in the current Chrome APIs. | |
https://github.com/GoogleChrome/developer.chrome.com/issues/2602#issuecomment-1110937788 | |
https://developer.chrome.com/docs/extensions/reference/action/#method-openPopup | |
*/ | |
// use this in your `background.js` service worker | |
// here, we check if we are on the Google home page or not and then show the appropriate popup | |
function setPopupForTab(tab) { | |
if (tab.url.startsWith('https://www.google.com/')) { | |
chrome.action.setPopup({ tabId: tab.id, popup: 'popup.html' }); | |
} else { | |
chrome.action.setPopup({ tabId: tab.id, popup: 'errorPopup.html' }); | |
} | |
} | |
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { | |
if (changeInfo.status === 'complete') { | |
setPopupForTab(tab); | |
} | |
}); | |
chrome.tabs.onActivated.addListener((activeInfo) => { | |
chrome.tabs.get(activeInfo.tabId, (tab) => { | |
setPopupForTab(tab); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment