How can i modify the host header

烂漫一生 提交于 2019-12-06 14:18:35

It looks like you shouldn't have difficulty doing this. Use onBeforeRequest

onBeforeRequest: Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to cancel or redirect requests.

Since this is triggered before any connection to the server is made, you should be able to modify the host header then [edit: if host header is not available, then use a redirect]. Make sure you have the "requestHeaders" permission in the manifest or else you won't see the request headers at all.

rob

@kzahel was right, and the note about redirection was spot on, here is my basic working code.

chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {
    if (details.url.indexOf('toast.txt') <= -1)
        return;
    details.requestHeaders.push({
        name: 'Host',
        value: 'testhost:80'
    });
    return { requestHeaders: details.requestHeaders };
}, {
    urls: ['http://*/*']
}, ['requestHeaders', 'blocking']);

chrome.webRequest.onBeforeRequest.addListener(function (details) {
    if (details.url.indexOf('sauce') <= -1)
        return;
    var url = 'http://127.0.0.1/toast.txt';
    return { redirectUrl: url };
}, {
    urls: ['http://*/*']
}, ['blocking']);

Admittedly a slightly odd example but it goes like this.

My local IIS has a site created that points to a folder that has a file "toast.txt", which is bound to "testhost".

Windows can no way of knowing about "testhost" e.g. cannot ping it.

With the extension running. Enter the address http://testhost/sauce

The extension notes the "sauce" in the "onBeforeRequest" method and redirects to "http://127.0.0.1/toast.txt" which in turn is picked up on by the "onBeforeSendHeaders" method where the "Host" header is added containing "testhost:80". All this occurs before the request leaves Chrome.

Now IIS receives the request "/toast.txt" that by itself would result in a 404, but because the "Host" header is set it pushes the request to the new website that is bound to "testhost" which then returns the "toast.txt" file.

Phew!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!