Reputation: 393
I have a url I want to open in my app using WebView
to avoid the user having to be redirected out of the app to the mobile browser. However the the web page I want to show requires some post parameters like from a post form. If it was a GET situation I woul'd have simply appended the parameters to the url.
<WebView
source={{uri: 'https://mypage.com/index.php', headers: '---', body: '---'}}
style={{marginTop: 20}}
/>
Do I put them in headers
or in body
, and in what format? Or is there another way? I would like to have the parameters in a key value format i.e cat=himalayan&dog=pug&fish=shark
Upvotes: 10
Views: 19109
Reputation: 369
We can do form post in webview in two ways
1st way:
const headerObj= { 'Content-Type': 'application/x-www-form-urlencoded'}
const postData = {
key1: value1,
key2: value2,
};
let urlEncodedData = '',
urlEncodedDataPairs = [],
key;
for (key in postData) {
urlEncodedDataPairs.push(
encodeURIComponent(key) + '=' + encodeURIComponent(postData[key]),
);
}
urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
<WebView
source={{uri: 'https://mypage.com/index.php', headers: headerObj, body: urlEncodedData, method:'POST'}}
style={{marginTop: 20}} />
2nd way: Using Html
<WebView
source={{html: `<html> <body onload="document.forms[0].submit();">
<form method="post" action=${this.state.URL}>
<input type="hidden" name="key1" value=${value1} >
<input type="hidden" name="key2" value=${tvalue2} >
</form >
</body> </html>`,}}
/>
Upvotes: 4
Reputation: 101
Put this piece of code in the body:
{ source: { uri: 'https://mypage.com/index.php', method: 'POST', body:
'cat=himalayan&dog=pug&fish=shark' }
Upvotes: 8
Reputation: 509
You will have to add method in the source prop like this
<WebView
source={{uri: 'https://mypage.com/index.php', headers: '---', body: '---',method:'POST'}}
style={{marginTop: 20}}
/>
Upvotes: 13