How to Change Chrome Extension Popups Dynamically
Learn how to change chrome extension popup windows dynamically using the Action API and window object.
Table of Contents 📖
Popups
Popups can either bet set in the manifest.json file or by using the Action API setPopup method. Below are two popups: login.html and profile.html that switch between one another on a button click.
<h1>Login Page</h1>
<h3>Click to Log In</h3>
<button id="button-login">Log In</button>
<script src="login.js"></script>
const buttonLogin = document.getElementById('button-login');
buttonLogin.addEventListener('click', async () => {
chrome.action.setPopup({popup: 'profile.html'});
});
<h1>Profile Page</h1>
<h3>Click to Log Out</h3>
<button id="button-logout">Log Out</button>
<script src="profile.js"></script>
const buttonLogout = document.getElementById('button-logout');
buttonLogout.addEventListener('click', async () => {
chrome.action.setPopup({popup: 'login.html'});
});
WARNING: The setPopup method takes a details object where one key is popup and the value is the location of the popup HTML file.
The code above works fine but an issue is that the popup change is only seen when the popup is closed and reopened. This is because the setPopup method only sets the HTML document to be opened when the user clicks on the extension icon.
Changing the Popup Instantly
To change the popup instantly, we need to use the window.location object of the popup.
const buttonLogin = document.getElementById('button-login');
buttonLogin.addEventListener('click', async () => {
await chrome.action.setPopup({popup: 'profile.html'});
window.location.assign('profile.html');
});
const buttonLogout = document.getElementById('button-logout');
buttonLogout.addEventListener('click', async () => {
await chrome.action.setPopup({popup: 'login.html'});
window.location.assign('login.html');
});
INFO: Popups are HTML documents with their own DOM. This means that they all have window objects that represent the window containing the DOM document.
The window.location object is used to load new documents, return the web protocol, etc. The assign method is used to load a new document into the window. Here, we load the new HTML document which causes the popup to change. Note that we still use the setPopup method to change the popup for the next extension icon click.