8

Is it possible to modify the HTTP request headers of a React Native WebView component on iOS?

I'm aware of the onShouldStartLoadWithRequest function but this doesn't seem to allow any possibility for modification.

Adam Terlson
  • 12,610
  • 4
  • 42
  • 63

2 Answers2

9

You can put your request header on attribute headers like this:

<WebView source={{
  uri: "http://blog.apentle.com/",
  headers: {
    Authorization: "Basic YXBlbnRsZS5jb206YXBlbnRsZQ==",
  }
}}
style={styles.webview} />
DoanND
  • 644
  • 8
  • 7
  • 1
    This does not apply headers to other requests made by the js code from the loaded page. Any idea how to implement it? – twboc May 21 '20 at 07:27
  • 2
    @AdamLagevik In a clean way? NO. What we had to do is to inject javascript into the web view that was loading other resources and add them by ourselves. There are a couple of stack overflow questions about that. https://stackoverflow.com/questions/56029978/adding-custom-headers-in-javascript-for-all-http-requests – twboc Jun 30 '20 at 07:09
  • WebView uses these headers just to fetch the content from URL you provided. It never sets any cookie or header in webview, you'll have to manage that on webpage itself. Check when the request is coming from mobile WebView and set header on response. – Mohd Shad Mirza Jul 15 '21 at 12:30
1

Yes, here is solution that works also for also for subsequent calls in the WebView - you can track the current URL, intercept new page loads, and navigate to them yourself (original credit for this technique to Chirag Shah from Big Binary)

const CustomHeaderWebView = (props) => {
  const { uri, onLoadStart, ...restProps } = props;
  const [currentURI, setURI] = useState(props.source.uri);
  const newSource = { ...props.source, uri: currentURI };

  return (
    <WebView
      {...restProps}
      source={newSource}
      onShouldStartLoadWithRequest={(request) => {
        // If we're loading the current URI, allow it to load
        if (request.url === currentURI) return true;
        // We're loading a new URL -- change state first
        setURI(request.url);
        return false;
      }}
    />
  );
};

<CustomHeaderWebView
  source={{
    uri: 'http://example.com',
    headers: {
      'my-custom-header-key': 'my-custom-header-value',
    },
  }}
/>;

Source: https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md#working-with-custom-headers-sessions-and-cookies

Stefan Majiros
  • 444
  • 7
  • 11