react-native-webview scalesPageToFit - ios - ios

In Webview props I set the scalesPageToFit prop to false.
In android OS I get nice and good view of the webview.
but on IOS I get small view of the webview as shown in desktop, because this prop is not supported in IOS.
I tried to add the property contentMode={'mobile'} but no change.
is there any other prop that might do the job or is there anything else that could help?
Environment:
OS: Ios
OS version: *
react-native version: 0.63.4
react-native-webview version: 10.9.2, 11.0.0

I used injectedJavaScriptBeforeContentLoaded as prop of the webview and injected meta label to the head tag of the html.
this is the code I injected
setTimeout(function () {
var met = document.createElement('meta');
met.content = 'width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1';
met.charset = 'UTF-8';
met.name = 'viewport';
var head = document.getElementsByTagName("head")[0];
head.append(met);
}, 500)

Uri's example worked and as I dug into this more to find out why I simplified the solution for my project. I had control of the html the device was trying to show so I changed the meta tag to:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
I found this on w3 schools article on viewports https://www.w3schools.com/css/css_rwd_viewport.asp
You could use Uri's meta code to insert the above if needed.

Here's what worked for me:
My webview:
<View style={styles.viewWrapper}>
<WebView onNavigationStateChange={this.onNavigationStateChange} ref=.
{this.WEBVIEW_REF} style={styles.webviewStyle} source={{ uri:
this.state.link }} />
</View>
My styles:
import {
Dimensions
} from 'react-native';
const deviceHieght = Dimensions.get('window').height;
const webViewHieght = deviceHieght-80;
viewWrapper: {
height: webViewHieght
},
webviewStyle: {
width: '100%',
height: 50000,
flex: 1
},
The reason why I'm subtracting 80 from deviceHeight is because of the size of my header. I've set the height of my webviewStyle very high because I have a long webpage that I want people to be able to scroll down. The page this webview is in has an outer view with a flex of 1.
So basically, for your needs I would just modify this to be whatever height and width you want.

Related

How to set height of React Native Webview? [duplicate]

Hi I know it's a known issue about the auto height of webview in react native,
and I have tried all the possibles solutions I've found on the internet such as :
https://gist.github.com/epeli/10c77c1710dd137a1335
https://github.com/danrigsby/react-native-web-container/blob/master/index.js
and all the solutions suggested in:
React native: Is it possible to have the height of a html content in a webview?
But unfortunately none of these seems to work for me,
I understand that the workaround they all suggest is to set the title to the height, but in my case it seems that the title always stays the same which is :
"text/html ...." and the rest of my html.
I get the html content from an API, it comes without a body, head or html tags, I've also tried adding these tags manually to the html and nothing seems to work.
I would love to hear if anyone else had that problem and how did it get fixed.
I wrap WebView inside a View, and set the height from the View.
<View style={{ height: 200 }}>
<WebView
automaticallyAdjustContentInsets={false}
source={{uri: 'https://player.vimeo.com/video/24156534?title=0&byline=0&portrait=0'}}
/>
</View>
I just follow this guide: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native and succeeded in my work. Here is solution:
1. Define script to send document height to native env after loaded website.
2. Handle onMesssage of webview component and reset Height via state.
const webViewScript = `
setTimeout(function() {
window.postMessage(document.documentElement.scrollHeight);
}, 500);
true; // note: this is required, or you'll sometimes get silent failures
`;
...
constructor(props) {
super(props);
this.state = {
webheight:100,
}
...
<WebView style={{height: this.state.webheight}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
source={{uri: "http://<your url>"}}
onMessage={event => {
this.setState({webheight: parseInt(event.nativeEvent.data)});
}}
javaScriptEnabled={true}
injectedJavaScript ={webViewScript}
domStorageEnabled={true}
></WebView>
Hope that help!
A reliable implementation of this behavior is with useAutoheight hook from #formidable-webview/webshell library.
The latter allows to inject "features" into WebViews, e.g. scripts and behaviors.
In this example, we will use 3 features + the aforementioned hook:
HandleHTMLDimensionsFeature which is required by useAutoheight hook to get document size updates;
ForceResponsiveViewportFeature to work around mobile virtual viewport;
ForceElementSizeFeature to work around cyclic size constraints
This component should work with any webpage.
import React from 'react';
import makeWebshell, {
HandleHTMLDimensionsFeature,
ForceResponsiveViewportFeature,
ForceElementSizeFeature,
useAutoheight
} from '#formidable-webview/webshell';
import WebView from 'react-native-webview';
const Webshell = makeWebshell(
WebView,
new HandleHTMLDimensionsFeature(),
new ForceResponsiveViewportFeature({ maxScale: 1 }),
new ForceElementSizeFeature({
target: 'body',
heightValue: 'auto',
widthValue: 'auto'
})
);
export default function ResilientAutoheightWebView(props) {
const { autoheightWebshellProps } = useAutoheight({
webshellProps: props
});
return <Webshell {...autoheightWebshellProps} />;
}
More resources:
Try this on Expo
Full guide here.
Using postMessage and onMessage like below worked for me perfectly.
Credit to iamdhj
onWebViewMessage = (event: WebViewMessageEvent) => {
this.setState({webViewHeight: Number(event.nativeEvent.data)})
}
render() {
return (
<ScrollView>
<WebView
style={{ height: this.state.webViewHeight }}
source={{html: '...'}}
onMessage={this.onWebViewMessage}
injectedJavaScript='window.ReactNativeWebView.postMessage(document.body.scrollHeight)'
/>
</ScrollView>
)
}
The WebView has default styles. If you want to set height, you also need to add flex: 0, as stated in the documentation:
Please note that there are default styles (example: you need to add flex: 0 to the style if you want to use height property).
I made a little component to make this functionality reusable if it helps anyone!
import React, { useState } from "react";
import WebView from "react-native-webview";
const DynamicHeightWebView = (props) => {
const [height, setHeight] = useState(0);
const webViewScript = `
setTimeout(function() {
window.ReactNativeWebView.postMessage(document.documentElement.scrollHeight);
}, 500);
true; // note: this is required, or you'll sometimes get silent failures
`;
return <WebView
{...props}
style={{
...props.style,
height: height,
}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
onMessage={event => {
setHeight(parseInt(event.nativeEvent.data));
}}
javaScriptEnabled={true}
injectedJavaScript ={webViewScript}
domStorageEnabled={true}
useWebKit={true}
/>
}
export default DynamicHeightWebView;
Apparently the problem was I had javaScriptEnabled={false}.
After enabling it everything worked.
I waste whole day to fix the height issue but in the end I had to shift to another library
This one is easy and good
https://github.com/archriss/react-native-render-html
You can get the content height by injecting the JS code as suggested by #ken-ratanachai-s. Although, You will experience certain irregularities in some devices (Extra height after the content). This is becuase the javascript returns the content height in pixels, but we need to use display points in react native. To fix this, Divide the height from javascript with the pixel ratio as follows.
import { WebView, PixelRatio } from 'react-native'
const [webviewHeight, setWebviewHeight] = useState(0)
const onProductDetailsWebViewMessage = event => {
setWebviewHeight(Number(event.nativeEvent.data)/PixelRatio.get())
}
return <WebView
originWhitelist={['*']}
style={{ height: productDetailsWebviewHeight }}
onMessage={onProductDetailsWebViewMessage}
injectedJavaScript='window.ReactNativeWebView.postMessage(document.body.scrollHeight)'
source={{ html: "..." }}
/>
Pixel ratio ref.: https://reactnative.dev/docs/pixelratio
Courtesy: https://stackoverflow.com/a/65976827/5321660
use package react-native-autoheight-webview
I recommend react-native-autoheight-webview.
it perfect work for me.
https://github.com/iou90/react-native-autoheight-webview
UPDATE:
Best answer is #Ken Ratanachai S.'s answer.
https://stackoverflow.com/a/65976827/9757656

Webview autoheight to content is not working on iOS (Appcelerator Titanium)

I want to add webview which height would be as it content. I make it running smoothly on Android but on iOS the longer the text is the longer space below text is.
Here is my code:
var window = Ti.UI.createWindow();
var scrollView = Ti.UI.createScrollView({
layout: 'vertical',
height: Ti.UI.SIZE
});
var view1 = Ti.UI.createView({
height: 200,
backgroundColor: 'red'
});
var webview = Ti.UI.createWebView({
height: Ti.UI.SIZE,
html: '<html><head><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2"></head><body style="margin:0; background-color: blue">Some page some text2</body></html>'
});
var view2 = Ti.UI.createView({
height: 200,
backgroundColor: 'green'
});
scrollView.add(view1);
scrollView.add(webview);
scrollView.add(view2);
window.add(scrollView);
window.open();
Thanks in advance.
The webview doesn't know the size of the content. But you can ASK the webview how high the content is.
For this you need to use evalJS.
Use the JS found on StackOverflow:
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
and preferably put this in a function inside the webview. Lets say the above Javascript is in function getDocumentHeight and that function returns the height property. Now, to get the height use eval like this:
var height = webview.evalJS('getDocumentHeight()');
webview.height = height;
Now, you want this to execute every time the content is loaded, assuming the content changes, so in that case you can watch the load event (doc here) and trigger the evalJS above every time this event is fired.
It will not be very pretty, as the webview is not intended to scale like this, but it works.
It seems it's a bug / discouraged method for iOS. No direct workaround. Can be checked here:
Jira Ticket about problem with iOS 9,
Jira Ticket about problem with webView + ScrollView

React native: webview height

Hi I know it's a known issue about the auto height of webview in react native,
and I have tried all the possibles solutions I've found on the internet such as :
https://gist.github.com/epeli/10c77c1710dd137a1335
https://github.com/danrigsby/react-native-web-container/blob/master/index.js
and all the solutions suggested in:
React native: Is it possible to have the height of a html content in a webview?
But unfortunately none of these seems to work for me,
I understand that the workaround they all suggest is to set the title to the height, but in my case it seems that the title always stays the same which is :
"text/html ...." and the rest of my html.
I get the html content from an API, it comes without a body, head or html tags, I've also tried adding these tags manually to the html and nothing seems to work.
I would love to hear if anyone else had that problem and how did it get fixed.
I wrap WebView inside a View, and set the height from the View.
<View style={{ height: 200 }}>
<WebView
automaticallyAdjustContentInsets={false}
source={{uri: 'https://player.vimeo.com/video/24156534?title=0&byline=0&portrait=0'}}
/>
</View>
I just follow this guide: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native and succeeded in my work. Here is solution:
1. Define script to send document height to native env after loaded website.
2. Handle onMesssage of webview component and reset Height via state.
const webViewScript = `
setTimeout(function() {
window.postMessage(document.documentElement.scrollHeight);
}, 500);
true; // note: this is required, or you'll sometimes get silent failures
`;
...
constructor(props) {
super(props);
this.state = {
webheight:100,
}
...
<WebView style={{height: this.state.webheight}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
source={{uri: "http://<your url>"}}
onMessage={event => {
this.setState({webheight: parseInt(event.nativeEvent.data)});
}}
javaScriptEnabled={true}
injectedJavaScript ={webViewScript}
domStorageEnabled={true}
></WebView>
Hope that help!
A reliable implementation of this behavior is with useAutoheight hook from #formidable-webview/webshell library.
The latter allows to inject "features" into WebViews, e.g. scripts and behaviors.
In this example, we will use 3 features + the aforementioned hook:
HandleHTMLDimensionsFeature which is required by useAutoheight hook to get document size updates;
ForceResponsiveViewportFeature to work around mobile virtual viewport;
ForceElementSizeFeature to work around cyclic size constraints
This component should work with any webpage.
import React from 'react';
import makeWebshell, {
HandleHTMLDimensionsFeature,
ForceResponsiveViewportFeature,
ForceElementSizeFeature,
useAutoheight
} from '#formidable-webview/webshell';
import WebView from 'react-native-webview';
const Webshell = makeWebshell(
WebView,
new HandleHTMLDimensionsFeature(),
new ForceResponsiveViewportFeature({ maxScale: 1 }),
new ForceElementSizeFeature({
target: 'body',
heightValue: 'auto',
widthValue: 'auto'
})
);
export default function ResilientAutoheightWebView(props) {
const { autoheightWebshellProps } = useAutoheight({
webshellProps: props
});
return <Webshell {...autoheightWebshellProps} />;
}
More resources:
Try this on Expo
Full guide here.
Using postMessage and onMessage like below worked for me perfectly.
Credit to iamdhj
onWebViewMessage = (event: WebViewMessageEvent) => {
this.setState({webViewHeight: Number(event.nativeEvent.data)})
}
render() {
return (
<ScrollView>
<WebView
style={{ height: this.state.webViewHeight }}
source={{html: '...'}}
onMessage={this.onWebViewMessage}
injectedJavaScript='window.ReactNativeWebView.postMessage(document.body.scrollHeight)'
/>
</ScrollView>
)
}
The WebView has default styles. If you want to set height, you also need to add flex: 0, as stated in the documentation:
Please note that there are default styles (example: you need to add flex: 0 to the style if you want to use height property).
I made a little component to make this functionality reusable if it helps anyone!
import React, { useState } from "react";
import WebView from "react-native-webview";
const DynamicHeightWebView = (props) => {
const [height, setHeight] = useState(0);
const webViewScript = `
setTimeout(function() {
window.ReactNativeWebView.postMessage(document.documentElement.scrollHeight);
}, 500);
true; // note: this is required, or you'll sometimes get silent failures
`;
return <WebView
{...props}
style={{
...props.style,
height: height,
}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
onMessage={event => {
setHeight(parseInt(event.nativeEvent.data));
}}
javaScriptEnabled={true}
injectedJavaScript ={webViewScript}
domStorageEnabled={true}
useWebKit={true}
/>
}
export default DynamicHeightWebView;
Apparently the problem was I had javaScriptEnabled={false}.
After enabling it everything worked.
I waste whole day to fix the height issue but in the end I had to shift to another library
This one is easy and good
https://github.com/archriss/react-native-render-html
You can get the content height by injecting the JS code as suggested by #ken-ratanachai-s. Although, You will experience certain irregularities in some devices (Extra height after the content). This is becuase the javascript returns the content height in pixels, but we need to use display points in react native. To fix this, Divide the height from javascript with the pixel ratio as follows.
import { WebView, PixelRatio } from 'react-native'
const [webviewHeight, setWebviewHeight] = useState(0)
const onProductDetailsWebViewMessage = event => {
setWebviewHeight(Number(event.nativeEvent.data)/PixelRatio.get())
}
return <WebView
originWhitelist={['*']}
style={{ height: productDetailsWebviewHeight }}
onMessage={onProductDetailsWebViewMessage}
injectedJavaScript='window.ReactNativeWebView.postMessage(document.body.scrollHeight)'
source={{ html: "..." }}
/>
Pixel ratio ref.: https://reactnative.dev/docs/pixelratio
Courtesy: https://stackoverflow.com/a/65976827/5321660
use package react-native-autoheight-webview
I recommend react-native-autoheight-webview.
it perfect work for me.
https://github.com/iou90/react-native-autoheight-webview
UPDATE:
Best answer is #Ken Ratanachai S.'s answer.
https://stackoverflow.com/a/65976827/9757656

White screen when load to new page

Hi i am new for jquery mobile 1.4.2. After i compile my application to apk and I also install to my phone which is android 4.3 . Everything is run quite smooth. But when i install to other phone which is android 4.2.Then the problem cum. When load to other page. The screen will keep white screen while loading to new screen.
I try below solution
$(document).bind("mobileinit", function () {
$.mobile.buttonMarkup.hoverDelay = 0;
$.mobile.defaultPageTransition = 'none';
$.mobile.defaultDialogTransition = 'none';
// $.mobile.page.prototype.options.domCache = true;
$.mobile.defaultHomeScroll = 0.
});
Change the meta
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no maximum-scale=1"" >
But i still having this issue . Any solution to fix this problem?
To avoid white screen add following css
.ui-mobile, .ui-mobile body{
background:url('bg_screen.png') no-repeat left top;
}
OR
Add color as you want
.ui-mobile, .ui-mobile body{
background:#999;
}

Phonegap: Keyboard changes window height in iOS 7

In iOS 6 everything works fine. The keyboard opens and moves the input into view. When the keyboard closes everything goes back where it should.
In iOS 7 the keyboard opens fine and the input remains in view. When the keyboard is closed the whole bottom half of the app is gone, though. I've tracked the issue down to the height of the window changing when the keyboard is opened, and not changing back when it's closed.
Right before the keyboard is opened the window height is 568 according to $(window).height() and after it's opened and after it's closed it is 828. The height of the document also changes accordingly.
I've attempted preventing the window from resizing with:
$(window).resize(function(e) {
e.preventDefault();
e.stopPropagation();
window.resizeTo(320,480);
return false;
});
I've also attempted to set the size back after the keyboard closes with no success.
I'm using phonegap 2.7 and have KeyboardShrinksView set to true.
I was seeing this too. After the height changes, some of our absolute positioned elements disappear off the bottom of the screen.
I found that with KeyBoardShrinksView = false in ios7, window.height stayed constant. This was the opposite of ios6 though, so a bit of a catch 22.
Not sure if there's a better way of handling this in Phonegap, but I put this in CDVViewController.m, created to config.xml files for ios < v7 and ios > v6, and my app works the way I want. Seemed a bit hacky, but not too disruptive of the rest of my code.
// read from config.xml in the app bundle
NSString* path = [[NSBundle mainBundle] pathForResource:#"config" ofType:#"xml"];
if (IsAtLeastiOSVersion(#"7.0")) {
path = [[NSBundle mainBundle] pathForResource:#"config_ios7" ofType:#"xml"];
}
(I also tried an app preference plugin at https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/ApplicationPreferences but don't think this was designed for this kind of preference.)
After I upgraded my project to iOS with cordova 3.1 I start having similar problems for the input fields in where I did not have the code listed above. The keyboard pushes things up and the header and footer did not returned to their original positions. I have tested and that solve the problem (maybe not very elegantly but it is a workaround). I just put that code on my pageinit event.
/*************************************************************************************************
* FIX: to avoid the buggy header and footer to jump and stick not
* to the top/bottom of the page after an input or textfield lost focus and the keyboard dissapear *
*************************************************************************************************/
$('input, textarea')
.on('focus', function (e) {
$('header, footer').css('position', 'absolute');
})
.on('blur', function (e) {
$('header, footer').css('position', 'fixed');
//force page redraw to fix incorrectly positioned fixed elements
setTimeout( function() {
window.scrollTo( $.mobile.window.scrollLeft(), $.mobile.window.scrollTop() );
}, 20 );
});
add code into CDVViewController.m
for example it added into webViewDidFinishLoad function
CGRect newFrame = self.webView.bounds;
NSLog(#"%f" , newFrame.size.height);
NSString *JS = [NSString stringWithFormat:#"viewport = document.querySelector('meta[name=viewport]'); viewport.setAttribute('content', 'user-scalable=no, initial-scale=1.0, maximum-scale=0.5, minimum-scale=0.5, width=device-width, height=%d, target-densitydpi=device-dpi');", (int) newFrame.size.height*2 ];
[self.webView stringByEvaluatingJavaScriptFromString:JS];
this code change <meta name="viewport" content="..."> and set height of device
set your viewport meta tag to your html
<meta name="viewport" content="width=device-width,height=**yourheight**, initial-scale=1, maximum-scale=1, user-scalable=0" >
or
<meta name="viewport" content="width=device-width,height=**device-height**, initial-scale=1, maximum-scale=1, user-scalable=0" >
The Petrash's solution worked for me. But I had still problems supporting rotations on iPad.
So, in the same CDVViewController.m I've added this method:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
if (self.webView){
CGRect newFrame = self.webView.bounds;
//NSLog(#"%f" , newFrame.size.height);
NSString *JS = [NSString stringWithFormat:#"viewport = document.querySelector('meta[name=viewport]'); viewport.setAttribute('content', 'user-scalable=no, initial-scale=1.0, maximum-scale=1, minimum-scale=1, width=device-width, height=%d, target-densitydpi=device-dpi');", (int) newFrame.size.height*1 ];
[self.webView stringByEvaluatingJavaScriptFromString:JS];
}
}
and, to support the "non scale" behaviour, edited the Petrash's solution in this way:
CGRect newFrame = self.webView.bounds;
//NSLog(#"%f" , newFrame.size.height);
NSString *JS = [NSString stringWithFormat:#"viewport = document.querySelector('meta[name=viewport]'); viewport.setAttribute('content', 'user-scalable=no, initial-scale=1.0, maximum-scale=1, minimum-scale=1, width=device-width, height=%d, target-densitydpi=device-dpi');", (int) newFrame.size.height*1 ];
[self.webView stringByEvaluatingJavaScriptFromString:JS];
KeyboardShrinksView = false
This is hacky, but it works from 5.1 to 7.0.3. Tested on Cordova 3.0.
After hours of investigating I've managed to get it to work:
My div, that is pushed up and never get's down again,
had the css attribute
position:fixed;
I switched this to
position:absolute;
and everything worked!
The best way I found was to put everything into a div and fix its height via javascript.
Works on modern Versions of both iOS (5, 6, 7) and Android (4.2, ...).
<style>
body {
overflow-y: scroll;
overflow-x: hidden;
webkit-overflow-scrolling: touch;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
body > .viewport{
position: absolute;
top: 0;
left: 0;
right: 0;
}
</style>
<body>
<div class='viewport'>
<!-- Put everything here -->
</div>
</body>
<script type="text/javascript">
$("body > .viewport").height($(document).height());
// WARNING: if your app works in both landscape and portrait modus, then you should reset the height of the container when the app changes orientation
</script>
I had a similar issue that drove me nuts for days. Not sure if this will help anyone else, but this is what solved it for me: (note I'm using jquery finger library to listen to tap events):
$('body').delegate("#send_feedback_button","tap", function(event){
$('textarea').blur();
event.stopImmediatePropagation();
// do my stuff
});
For me calling blur on any textarea in the view was the trick. The stopImmediatePropagation got rid of some other funkiness.
I had the same problem and I managed to track it down to dynamic content.
I had initially an empty div that was filled with text using javascript.
When I pre filled the div with static text the problem was gone.
Looks like this div's height was not counted when resizing.

Resources