原生脚本裸webview似乎不起作用

Nativescript bare webview doesnt seem to work

本文关键字:不起作用 webview 脚本 原生      更新时间:2023-09-26

我最近进入了原生脚本,我面临着一个问题,我似乎无法围绕它工作。

我想要完成的是打开一个基本的WebView并设置一个外部url来加载,如stackoverflow.com。

我在模拟器上运行这个Android api 17

app.js

var application = require("application");
application.mainModule = "main-page";
application.cssFile = "./app.css";
application.start();

main-page.js

var vmModule = require("./main-view-model");
var webViewModule = require("ui/web-view");
var webView = new webViewModule.WebView();
function pageLoaded(args) {
    var page = args.object;
    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">
  <StackLayout>
    <WebView id="webView" colSpan="4" row="2"/>
  </StackLayout>
</Page>

我还检查了INTERNET权限是否设置为application,并且是启用的。

同时应用程序停止工作,命令

tns运行android——模拟器

在模拟器上成功安装并运行应用程序后,它只是发送大量输出的垃圾邮件。

你能帮我理解它到底是怎么工作的吗?

tl;dr

由于某些原因你不能把WebView放在StackLayout中,它根本不显示。使用GridLayout代替。这是GitHub的一个问题。

<标题>完整的答案

Android模拟器确实是喋喋不休的,但在日志的某个地方(很可能在最后),几乎可以肯定有一个错误的堆栈跟踪。如果你用的是Mac, iOS模拟器就不会那么"喋喋不休"了。

也就是说,让我们来修复你的代码。下面是工作代码,注释显示了对代码的更改。

app.js

没有问题,看起来应该!

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>

我在这里做了一些事情。首先,我移除了colSpan="4" row="2"。那两个参数只用于GridLayouts,而你正在使用StackLayout。然而正如你所看到的,我已经把你的StackLayout变成了GridLayout。这样做的原因是,由于某些原因,你不能把WebView放在StackLayout中,它根本不显示。这是GitHub的一个问题。

替代解决方案

如果你想创建一个WebView显示Google,你可以直接在XML中设置url属性。如果你这样做,你甚至不需要Javascript。当然,如果你想动态设置url,你需要从Javascript中完成。

url属性设置示例:

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

属性url目前已被WebView弃用。