Can a Safari extension detect a page navigation error?

When the user tries to open a non-existing URL such as https://dsjiksfdakjf.com, Safari shows a built-in error page that displays texts like this:

Safari Can’t Find the Server

Safari can’t open the page “https://dsjiksfdakjf.com%E2%80%9D because Safari can’t find the server “dsjiksfdakjf.com”.

Can a Safari extension detect when this happen?

Background of question

I'd like to allow users to redirect from a broken or censored (HTTP 451) URL to another URL as a fallback, so that my users won't loose what they can still do other than just closing the tab.

I've been looking for the solution but so far, no luck. I couldn't find out such functionalities from SFSafariExtensionHandler, SFSafariPage, etc. JavaScript files of extensions are not loaded for that error page either. I even wonder if it actually can't detect and what I can do for now is just to submit the feedback to Apple...

Answered by jw732 in 692460022

What API would you use to build this?

A solution for this off the top of my head, whilst using the WebExtension API goes something like this.

JavaScript files of extensions are not loaded for that error page either. 

That's right. Content scripts are not loaded in that kind of error page. The background page is loaded however.

You could try to listen for browser.webNavigation.onCompleted and then check the currently active tab:

browser.tabs.query({currentWindow: true, active: true}, tabs => {
    const active = tabs[0];
    // do something with the tab data
});

You could read the active.title and derive if the page failed to load or even run your own fetch and get the status code back and decide what to do from there.

I haven't tested this so I can't confirm whether or not browser.webNavigation.onCompleted actually fires for those kind of error pages, but worth a try if you're invested in this.

Accepted Answer

What API would you use to build this?

A solution for this off the top of my head, whilst using the WebExtension API goes something like this.

JavaScript files of extensions are not loaded for that error page either. 

That's right. Content scripts are not loaded in that kind of error page. The background page is loaded however.

You could try to listen for browser.webNavigation.onCompleted and then check the currently active tab:

browser.tabs.query({currentWindow: true, active: true}, tabs => {
    const active = tabs[0];
    // do something with the tab data
});

You could read the active.title and derive if the page failed to load or even run your own fetch and get the status code back and decide what to do from there.

I haven't tested this so I can't confirm whether or not browser.webNavigation.onCompleted actually fires for those kind of error pages, but worth a try if you're invested in this.

Can a Safari extension detect a page navigation error?
 
 
Q