Osbourne Ruddock
Osbourne Ruddock

Reputation: 455

How to get chrome.webRequest.onBeforeRequest.addListener() to fire at Chrome startup?

I am working on an extension for Chrome that utilizes a native messaging host. My background.js registers a listener immediately to process all onBeforeRequest events (i.e., all requests) and pass them on to the native helper application. This is all well and good when a page is visited after Chrome has started up, but when I click a URL that launches Chrome, my listener does not fire.

Here is the basic structure of the listener at the top of my background.js:

chrome.webRequest.onBeforeRequest.addListener(function (details) {
    alert('forwarding request!');
    chrome.runtime.sendNativeMessage('<extension name>', { url: details.url });
}, { urls: ['http://*', 'https://*'] }, ['blocking']);

Obviously, there are conditions in place that determine whether to pass off the request and block it in Chrome, but they are not relevant here. Even without the sendNativeMessage bit, I cannot produce an alert for the URL that is clicked to launch an instance of Chrome.

Any clever ways to register this listener before the first request at startup goes through?

Upvotes: 2

Views: 2674

Answers (2)

rsanchez
rsanchez

Reputation: 14657

You can try giving your extension the background permission:

Makes Chrome start up early and and shut down late, so that apps and extensions can have a longer life.

When any installed hosted app, packaged app, or extension has "background" permission, Chrome runs (invisibly) as soon as the user logs into their computer—before the user launches Chrome. The "background" permission also makes Chrome continue running (even after its last window is closed) until the user explicitly quits Chrome.

This way the Chrome process and extensions will be loaded before you click any URL. The user can still circumvent this by explicitly killing the Chrome process.

As a side note, keep in mind that the response from your onBeforeRequest listener needs to be synchronous if you want to block a request, so you can't base the decision to block on the response from a native messaging host.

Upvotes: 2

Rob W
Rob W

Reputation: 348992

One way to solve the problem is to use the chrome.declarativeWebRequest API to declaratively register a webRequest listener. The disadvantage of this API is that it is only available to Chrome users on the beta and dev channel at the moment, and less flexible than the webRequest API (the rules are declarative, so you cannot make runtime decisions about request handling that are not supported by the DWR API).

Another way to work around the problem is to use chrome.tabs.query to find tabs that had been opened before the extension was launched.

Upvotes: 2

Related Questions