Nativescript bare webview doesnt seem to work

情到浓时终转凉″ 提交于 2019-12-03 20:58:55

tl;dr for others having problems with WebView

For some reason you can't put a WebView in a StackLayout, it simply does not show. Use a GridLayout instead. There's a GitHub issue on this.

Full answer

The Android emulator is really chatty but somewhere in that log (most probably in the end) there's almost certainly a stack trace with the error. If you're running a Mac, the iOS emulator is much less chatty.

That said, let's fix your code. Below is working code, commented to show the changes to your code.

app.js

No problem there, looking as it should!

main-page.js

/**
 * Do you actually have a file called 'main-view-model.js' in the same
 * folder as this file? In any case, it's not used in your example code
 * so I commented it out.
 */
//var vmModule = require("./main-view-model");
var webViewModule = require("ui/web-view");

/**
 * Here you are creating a NEW webview. If you want to, you can create
 * element dynamically and then attach them to the view. However, in your
 * example you already have a webview in your xml file so there's no need
 * to create a new one.
 */
//var webView = new webViewModule.WebView();

function pageLoaded(args) {
    var page = args.object;
    /**
     * Corrected the line below. What you're doing here is pretty
     * much equal to $('#webView') in jQuery. You're selecting
     * an element
     */
    var web = page.getViewById("webView");
    //var web = page.getViewById(webViewModule.WebView,"webView");
    web.url = "http://google.com";

}
exports.pageLoaded = pageLoaded;

main-page.xml

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
    <GridLayout>
        <WebView id="webView" />
    </GridLayout>
</Page>

So I've done a couple of things here. First, I've removed the colSpan="4" row="2". Those two parameters are only used for GridLayouts, and you're using a StackLayout. However as you can see I've changed your StackLayout into a GridLayout. Reason for this is that for some reason you can't put a WebView in a StackLayout, it simply does not show. There's a GitHub issue on this.

Alternative solution

If all you want to do is to create a WebView showing Google, you can just set the url property directly in the XML. If you're doing it this way you don't even need the Javascript. Of course, if you want to dynamically set the url you need to do it from the Javascript.

Example of setting url property:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
    <GridLayout>
        <WebView id="webView" url="http://www.google.com" />
    </GridLayout>
</Page>

Attribute url is currently deprecated for WebView. Use src instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!