0

There are several guides on how to disable onbeforeunload when the user clicks on the submit button. However, I can't find a guide that fits my case.

My Chrome Extension injects onbeforeunload Javascript into specific web pages. In those web pages, there are two buttons that both saves the form and leaves the page. Each button is tied to a function named opSubmit('T') and opSubmit('S')

What I want to do is, I want to disable onbeforeunload when those two functions are called (so that onbeforeunload doesn't throw confusing messege at users after they click save.). I can't get to know how to do this. I am attaching the elements code of those two buttons. Elements

I am also attaching my code:

background.js

chrome.tabs.onActivated.addListener( function(activeInfo){
    chrome.tabs.get(activeInfo.tabId, function(tab){
        y = tab.url;
    if(y == "http://inje.u-folio.com/st/clinical-training/inpatient/pomr/create") {
        chrome.tabs.executeScript({
                file: '/js/inject.js'
            });
        };
     };
});

inject.js

window.onbeforeunload = function(e) {
    e.preventDefault();
    return true;
};

Edit)

In short, I want to disable my 'inject.js's onbeforeunload event if a button on the webpage is clicked.

The button click calls a function called opSubmit(). I want to know whether if I can disable my 'inject.js's onbeforeunload event by overriding the page's opSubmit() function. I found this(Use a content script to access the page context variables and functions), but can't apply it to my case. Any help will be greatly appreciated.

  • See [How to remove the ‘leave site ’ pop up While updating the url of the current active page in chrome extension](https://stackoverflow.com/a/60487374) – wOxxOm Aug 20 '22 at 12:12
  • @wOxxOm I don't think that answer fits my case... In my case, the buttons on the webpage shows a dialog asking user whether to save, saves a form after user clicks on 'OK', and leaves the page. Not changing to specific URLs. – Alternative415 Aug 20 '22 at 12:29
  • Assuming the page really uses beforeunload event, the answer explains how to disable it. The URL doesn't matter. – wOxxOm Aug 20 '22 at 12:56
  • @wOxxOm No, the page doesn't have any beforeunload event. I injected those by my chrome extension(see inject.js above). I want to disable my inject.js's beforeunload if the button on the page is clicked. – Alternative415 Aug 20 '22 at 13:41
  • @wOxxOm I edited the main post to clarify my intention. I would be greatful if you have a look at it. – Alternative415 Aug 20 '22 at 13:49
  • You can add a click listener for these elements with `true`: elem.addEventListener('click', toggle, true); function toggle() { window.onbeforeunload = null } – wOxxOm Aug 20 '22 at 14:28

0 Answers0