Nativescript: How to add custom HTTP headers in WebView?

Created on 11 Oct 2016  路  4Comments  路  Source: NativeScript/NativeScript

Please, provide the details below:

Did you verify this is a real problem by searching Stack Overflow and the other open issues in this repo?

Yes.

Which platform(s) does your issue occur on?

Both

Please tell us how to recreate the issue in as much detail as possible.

Is there any way to add custom HTTP headers in WebView? I searched issues, Stack Overflow, and API document, but I couldn't find how to do it specifically.

We might need a NativeScript plugin implementing like this native code?

BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"my custom header"]!=nil;

if(headerIsPresent) return YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [request URL];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        // set the new headers
        for(NSString *key in [self.customHeaders allKeys]){
            [request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
        }

        // reload the request
        [self loadRequest:request];
    });
});
return NO;

I would appreciate your help.

question

All 4 comments

Hello @okmttdhr

Providing custom headers for WebView requests is not supported out-fo-the box even in the native iOS environment so it is not supported out-of-the-box in nativeScript as well. However, based on the possible solutions you have found (not sure if the example above would work thou due to the considerations for not supporting multiple frames/redirects).

Stil,l with the guiding articles in the runtime references and in the plugins sections, you can develop your own plugin.

@\NickIliev
I created this repository showing the example implementing custom headers for WebView requests.

Thank you very much for your reply.

Hey guys,

I needed to pass a few custom headers today and found the code in @okmttdhr's repo, so THANKS!

A few things didn't work, especially on newer Android devices, so I had to make a bunch of adjustments. I've also turned it into a plugin so others may easily benefit of our combined efforts as well: https://github.com/EddyVerbruggen/nativescript-webview-utils

Cheers,
Eddy

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings