To add an on/off switch to your Chrome extension, you can follow these steps:
let isEnabled = true;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "toggle") {
isEnabled = !isEnabled;
}
});
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ isEnabled });
});
chrome.browserAction.onClicked.addListener((tab) => {
isEnabled = !isEnabled;
chrome.storage.sync.set({ isEnabled });
chrome.tabs.sendMessage(tab.id, { message: "toggle", isEnabled });
});
<button id="toggle-btn">On</button>
function toggle() {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { message: "toggle" }, (response) => {
updateUI(response.isEnabled);
});
});
}
function updateUI(isEnabled) {
const toggleBtn = document.getElementById("toggle-btn");
if (isEnabled) {
toggleBtn.textContent = "Off";
} else {
toggleBtn.textContent = "On";
}
}
document.addEventListener("DOMContentLoaded", () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { message: "getIsEnabled" }, (response) => {
updateUI(response.isEnabled);
});
});
document.getElementById("toggle-btn").addEventListener("click", toggle);
});
let isEnabled;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "toggle") {
isEnabled = request.isEnabled;
// Disable or enable feature depending on isEnabled
} else if (request.message === "getIsEnabled") {
sendResponse({ isEnabled });
}
});
With these changes, your extension should now have an on/off switch that allows users to toggle its behavior.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-12 16:30:40 +0000
Seen: 13 times
Last updated: May 12 '23
What is the process for altering svn branches with git-svn?
What is the process to italicize certain keywords in visual studio code?
What is the process for developing a JTable that has both row and column headers?
What is the process for removing a dat.GUI element?
How to solve the issue "process is running" in Visual Studio Debugging?
What is the process of moving information from one tab to another in Excel by transposing it?
What is the process of dividing the WSD dataset (in CSV format) into tokens called?
What is the process of uploading a file using NextJS and formidable?
What is the process for using pnpm to build a single workspace only?