iThink icon indicating copy to clipboard operation
iThink copied to clipboard

react-native webview change user-agent

Open hufeng opened this issue 7 years ago • 0 comments

change User-Agent

//android
<WebView
  //for-example
   userAgent="demo-react-native-app" 
  //modify header
  source={{
    uri: 'https://xxx',
    headers: {{
       "X-DemoApp-Version": "1.1",
       "X-DemoApp-Type": "demo-app-react-native"
    }}
  }} 
/>
//in AppDelegate.m
NSString *newAgent = @"demo-react-native-app";
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

get html

//mock postMessage
//https://github.com/facebook/react-native/issues/10865
(${String(function() {
            var originalPostMessage = window.postMessage;
            var patchedPostMessage = function(message, targetOrigin, transfer) {
              originalPostMessage(message, targetOrigin, transfer);
            };
            patchedPostMessage.toString = function() {
              return String(Object.hasOwnProperty).replace(
                'hasOwnProperty',
                'postMessage'
              );
            };
            window.postMessage = patchedPostMessage;
          })})();
          window.onload = function() {
            function maxScrollWatch(callback) {
              var count = 0;
              var height = window.innerHeight;
              window.scrollTo(0, 0);
            
              var id = setInterval(() => {
                count++;
                window.scrollTo(0, height / 2 * count);
              }, 20);
            
              setTimeout(() => {
                clearTimeout(id);
                callback();
                return;
              }, 4000);
            }
            
            maxScrollWatch(function() {
//notify rn
              window.postMessage('finish');
//notify rn
              window.postMessage(document.documentElement.outerHTML);
            });
          }

hufeng avatar Sep 20 '17 06:09 hufeng