I am trying to create a pretty simple chrome extension that enables me to navigate the browser back and forward using horizontal scrolling. I want to be able to enable and disable the extension; however I want the state to persist when the tab changes (whether the active tab is a new url or a new tab is launched).
Here is my current code that partially works for only the active tab:
manifest.json:
{
"name": "SwipeNav",
"action": {},
"manifest_version": 3,
"version": "0.1",
"description": "Navigates browser forward and back with 2 finger swiping",
"permissions": [
"activeTab",
"scripting",
"tabs",
"alarms"
],
"background": {
"service_worker": "background.js"
}
}
background.js
function twoFingerBack() {
console.log("Enabling 2 finger scrolling");
let timer;
window.addEventListener("wheel", function(event) {
clearTimeout(timer);
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
timer = setTimeout(function() {
if (event.deltaX > 0) {
history.back();
} else if (event.deltaX < 0) {
history.forward();
}
}, 200);
}
});
}
function removeExt() {
console.log("Disabling 2 finger scrolling");
window.removeEventListener("wheel", removeExt)
}
let enabled = true;
chrome.action.onClicked.addListener((tab) => {
enabled = !enabled;
if (enabled) {
if (!tab.url.includes("chrome://")) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: twoFingerBack
});
}
} else {
if (!tab.url.includes("chrome://")) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: removeExt
});
}
}
});
I have read that I can use chrome.tabs.onActivated
however I could not get this to work at all. Not sure if that is the right path.
Any help is appreciated...thanks!