-2

I am developing a Google Chrome extension, and if the user goes to a site that doesn't exist, like thiswebsitedoesnotexist.com, I want the extension to redirect them to another page set specifically by me. I am not talking about sites that give 404 errors. I mean sites whose DNS server address cannot be found, so Google Chrome gives you it's standard error page.

I tried using window.location.href = *link*, but that doesn't change the webpage. How can I get around this? Thanks in advance.

Cameron Payton
  • 362
  • 1
  • 7
  • 17

1 Answers1

0

Why won't window.location.href work on error pages?

Because, in fact, you are being shown a document with a data: URL for internal error pages, despite the address bar showing the intended address. You can verify that with DevTools by inspecting window.location in the error page.

data: URLs are not scriptable by Chrome extensions: no host permission allows to inject content scripts into them.

Therefore, attempts to programmatically inject a content script that changes window.location.href (or does console.log) will fail due to missing permissions, and match patterns for content scripts in the manifest won't apply.

How can I get around this?

You can use chrome.tabs.update from the background page to navigate away from the error page.

To detect such an error in a background page, probably the best fit is to use chrome.webNavigation API, though using chrome.webRequest API is also possible (careful with filters, and requires broad permissions). Both will provide tabId to do this.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • Thank you! This was really helpful (more helpful than that stuart guy). I have a second question. I call console.log from the background page, but it doesn't seem to execute! Do you have a solution for this? – Cameron Payton Jul 11 '16 at 14:41