user5858
user5858

Reputation: 1221

get the document url in chrome.webRequest.onBeforeRequest

In chrome.webRequest.onBeforeRequest we get all sorts of url's -- javascript, css etc.

For every url I want to know the main tab url.

What is the simplest way to get it synchronously?

Right now I'm using this way:


if details.frameId == 0 then details.url contains the main tab url for this tab id

chrome.webRequest.onBeforeRequest.addListener(
        function (details) {

            if (details.tabId == -1)
            {
                return;
            }


            if ("type" in details && ['main_frame', 'sub_frame'].indexOf(details.type) !== -1)
            {
                if (details.frameId == 0) {
                    all_tabs_info.add_tab_info(details.tabId, details.url);
                }
            }


        },
        {
            urls: ['<all_urls>']
        },
["blocking"]);


So now onwards if any request comes for this tab id we already have the tab url. This crude logic seems to be working.

Upvotes: 2

Views: 1572

Answers (1)

woxxom
woxxom

Reputation: 73806

A couple of enhancements:

  • use filters as much as possible, in this case for type.
  • main_frame type by definition corresponds to the top-level frame, which in turn means it has frameId of 0, so by not listening to sub_frame you can omit the check altogether.

    The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.

  • type is not optional as you can see in the documentation, no need to doubt its presence.

So the simplified code is just this:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if (details.tabId >= 0) {
            all_tabs_info.add_tab_info(details.tabId, details.url);
        }
    },
    {
        urls: ['<all_urls>'],
        types: ['main_frame'],
    },
    ["blocking"]
);

Upvotes: 2

Related Questions