Background
I have a Chrome extension with a browser action to launch index.html
in a new tab.
I'd like to update the extension to open index.html
in a popup first, and then include a button users can click to optionally open the app in a new tab.
I don't want this button to show when it's not a popup (since it wouldn't make sense), which means the content script needs to know whether it is a popup in order to show the button.
Questions
This is a two part question:
- How does a Chrome extension popup know it's a popup?
- How do I pass that information to a content script before the popup is rendered?
What I've tried
I've tried to use chrome.extension.getViews
in background.js
to firstly determine if a popup is open. Then, I send a message to the content script which then shows the button. However I haven't gotten it to work - views
is always an empty array, and the message doesn't seem to ever be received by the content script.
Here are the relevant parts of my manifest.json
file:
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": {
"19": "img/icon19.png",
"38": "img/icon38.png"
},
"default_title": "Super Simple Tasks",
"default_popup": "index.html"
}
And here's what I've been trying in my background.js
:
// Get all popups
var views = chrome.extension.getViews({ type: "popup" });
// Send a message if there is a popup
if (views.length > 0){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "popup_open"}, function(response) {});
});
};
And then in my content script, I listen for the message and then add a class to the body:
// Listen for the message
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action === 'popup_open') {
// My code here to show the button
}
});