I am trying to make a Chrome Extension that prevents user from accidently refreshing/reloading/exiting in a certain webpage.
Put simple, I want to make a Chrome Extension that behaves the same as this extension(https://github.com/m-primo/Dont-Leave), but only on a certain webpage(I have a URL).
After inspecting some codes and googling, I think the API 'onbeforeunload' perfectly fits my needs.
I used content script to make the script work only in the specific webpage. However, this seems to be causing an issue. It seems that it wouldn't work in Contect Script due to limitations(https://developer.chrome.com/docs/extensions/mv3/content_scripts/).
How can I make my extension work? Should I use a different method(using background.js?)? If then, how can I make my extention recognise specific web pages?
Any specific examples will be welcome (I am a total newbie in any kind of programming)
My code:
Manifest.json
{
"manifest_version": 2,
"name": "Sample",
"description": "Sample description",
"version": "1.0",
"content_scripts":[
{
"matches":[
"http://sample.com"
],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"storage",
"https://ajax.googleapis.com/"
]
}
content.js
window.onbeforeunload = function(e) {
e.preventDefault();
return true;
};
Edit) So I decided to ditch using Content Script. My new code just uses background.js. It looks like this:
chrome.tabs.onActivated.addListener( function(activeInfo){
chrome.tabs.get(activeInfo.tabId, function(tab){
y = tab.url;
if(y == "sample.com") {
alert("Mistake stopper activated.")
window.onbeforeunload = function() {
return true;
};
}
});
});
I can see the "mistake stopper activated" message when I open the website I want now, but the onbeforeunload API doesn't work at all. What am I possibly missing?