Search code examples
iosangularnativescript

How can I make a height dynamic in iOS with WebView, Nativescript?


The problem I have is that the WebView does not load height dynamically in iOS (in Android if it does), the question is that my content is dynamic and can grow high, and putting the fixed height would not work for me. Could you help me?

<CardView *ngFor="let itinerario of itinerario" class="card" elevation="40" radius="10" ios:shadowRadius="3">
   <StackLayout class="card-layout text-center">
      <WebView [src]="itinerario.mEstructura" height="auto"></WebView>
   </StackLayout>
</CardView>

Solution

  • Use native method to evaluate JavaScript that can return height of the document.

    HTML

    <GridLayout>
        <ScrollView class="page">
            <StackLayout>
                <WebView src="https://www.nativescript.org/" [height]="height"
                    (loadFinished)="onWebViewLoadFinished($event)"></WebView>
                <Button class="btn btn-primary" text="Hello!"></Button>
            </StackLayout>
        </ScrollView>
    </GridLayout>
    

    TS

     onWebViewLoadFinished(event: EventData) {
        const webView = <WebView>event.object,
            jsStr = `var body = document.body;
            var html = document.documentElement;
            Math.max( body.scrollHeight, body.offsetHeight, 
            html.clientHeight, html.scrollHeight, html.offsetHeight);`;
    
        if (webView.ios) {
            webView.ios.scrollView.scrollEnabled = false;
            webView.ios.evaluateJavaScriptCompletionHandler(jsStr,
                (
                    result,
                    error
                ) => {
                    if (error) {
                        console.log("error...");
                    } else if (result) {
                        this.height = layout.toDeviceIndependentPixels(result);
                        this.changeDetectorRef.detectChanges();
                    }
                });
        } else if (webView.android) {
            // Works only on Android 19 and above
            webView.android.evaluateJavascript(
                jsStr,
                new android.webkit.ValueCallback({
                    onReceiveValue: (height) => {
                        this.height = layout.toDeviceIndependentPixels(height);
                        this.changeDetectorRef.detectChanges();
                    }
                })
            );
        }
    }
    

    Playground Sample