Search code examples
javascriptajaxgoogle-chromegoogle-chrome-extensionhttp2

Detect if URL supports HTTP2 using AJAX request in Chrome Extension?


I want the user to be able to enter their website URL into an input box that is part of a Chrome Extension and the Chrome extension will use an AJAX request or something similar to detect and tell the user if the server behind the URL supports sending responses via HTTP2. Is this possible?

Maybe the WebRequest has a way of picking up this information? Or the new Fetch API? Could your request tell the server somehow that only HTTP2 replies are understood? I can't see an obvious way.

I know you can use window.chrome.loadTimes().connectionInfo to get the protocol of the current page but this requires loading the whole page which I don't want to do.

Example URLS:

Delivered over HTTP2: https://cdn.sstatic.net/

Delivered over HTTP 1.1: https://stackoverflow.com/


Solution

  • HTTP/2 responses require a "status" response header - https://http2.github.io/http2-spec/#HttpResponse, so to check whether the response is using HTTP/2, you can use the chrome.webRequest.onHeadersReceived event with "responseHeaders" in extraInfoSpec. For example, with your test cases:

    chrome.webRequest.onHeadersReceived.addListener(function(details) {
        var isHttp2 = details.responseHeaders.some(function(header) {
            return header.name === 'status';
        });
        console.log('Request to ' + details.url + ', http2 = ' + isHttp2);
    }, {
        urls: ['https://cdn.sstatic.net/*', 'http://stackoverflow.com/*'],
        types: ['xmlhttprequest']
    }, ['responseHeaders']);
    
    // Tests:
    fetch('http://stackoverflow.com');
    fetch('https://cdn.sstatic.net');