Jonathan Wong
Jonathan Wong

Reputation: 58

How exactly does the following Chrome Extension javascript code snippet work?

I don't get the {urls: ["://www.mysite.com/.js"]}, ["blocking"]); part. This code can be found @ Chrome extension to modify page's script includes and JS with the slight (forced) modification of mysite(dot)com to example.com due to stackoverflow rules.

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if( details.url == "http://www.example.com/js/library.js" )
            return {redirectUrl: "http://www.example.com/js/library_dev.js" };
    },
    {urls: ["*://www.example.com/*.js"]},
    ["blocking"]);

Upvotes: 1

Views: 118

Answers (1)

Nate
Nate

Reputation: 553

The second parameter of onBeforeRequest.addEventListener is an optional requestFilter object.

It has four additional properties

  • urls (optional array of string)
    • Each element is a URL or URL pattern. Please refer to content script match patterns for URL pattern definition. Requests that cannot match any of the URLs will be filtered out.
  • types (optional array of string)
    • Each element is a request type described above. Requests that cannot match any of the types will be filtered out.
  • tabId (optional integer)
    • The ID of the tab in which requests takes place.
  • windowId (optional integer)
    • The ID of the window in which requests takes place.

So urls: ["*://www.example.com/*.js"]} is adding a URL filter to the onBeforeRequest listener.

This is attempt to match any request for a javascript file on the www.example.com domain. Using http or https

[(scheme) *] :\\ [(host) www.example.com] / [(path) *.js]

<url-pattern> := <scheme>://<host><path>
<scheme> := '*' | 'http' | 'https' | 'file' | 'ftp'
<host> := '*' | '*.' <any char except '/' and '*'>+
<path> := '/' <any chars>

https://developer.chrome.com/extensions/match_patterns


The third parameter ['blocking'] is an optional array of strings used for extra information. This modifies how Chrome returns your callback.

Since it contains "blocking", the callback function is handled synchronously. That means that the request is blocked until the callback function returns. So for onBeforeRequest you could use this to cancel or redirect a request before it happens.

More info available here:

https://www.chromium.org/developers/design-documents/extensions/proposed-changes/apis-under-development/notifications-of-web-request-and-navigation

Upvotes: 1

Related Questions