nitobuendia
nitobuendia

Reputation: 1248

Load content_script.js when ERR_NAME_NOT_RESOLVED

I have a test Chrome Extension which runs on <all_urls>. It runs a content_script which just writes the domain.

It works fine in all cases, except when I write domains that do no exist.

The purpose of the Extension is to run on a particular domain, regardless of what it happens. Hence, I want to make sure that it runs when I hit ERR_NAME_NOT_RESOLVED too.

Any ideas on how to achieve it?


manifest.json

{
  "manifest_version": 2,

  "name": "Test",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ],

  "permissions": [
    "<all_urls>"
  ]

}

content_script.js

window.console.log(window.document.location.hostname);

Upvotes: 1

Views: 561

Answers (2)

nitobuendia
nitobuendia

Reputation: 1248

Found an answer:

While content_script is not possible, you can interact with the request with webRequest and make changes to it. This fulfils my needs.

There are some examples on Chrome Developer documentation. Otherwise, this is my new code:


manifest.json

{
  "manifest_version": 2,

  "name": "Lazy ShortCuts",
  "version": "1.0",

  "background": {
    "scripts": ["background.js"]
  },

  "permissions": [
    "<all_urls>",
    "webRequest",
    "webRequestBlocking",
  ]

}

background.js

chrome.webRequest.onBeforeRequest.addListener(
  function(info) {
    console.log("Data intercepted: ", info);
    return {redirectUrl: 'https://google.com'};
  },
  {
    urls: [
      "<all_urls>",
    ]
  },
  ["blocking"]
);

Upvotes: 1

Xan
Xan

Reputation: 77531

In case that you're trying to visit a non-existent domain, you're shown a Chrome internal error page with a data: URL.

This is not a valid match even for <all_urls>, so you can never inject into such pages.

If you need to capture navigation failures, you can do so via webNavigation or webRequest APIs from a background page; but you won't be able to modify the error pages.

Upvotes: 1

Related Questions