问题
I've been trying to figure out a way to get a local webpage content to load and set the webview html content in native script. I've successfully got it working on the simulator but it doesn't seem to work on the device. I've googled around and most people are saying that I need to locate my html files in the 'Documents' dir of my app, but as far as I can see there is no way to get the files I need there when I deploy the app. Can anyone else shed some light on the ways to get files located in the documents folder of the app on deploy or copying them there at runtime. Thank you
var createViewModel = require("./main-view-model").createViewModel;
var orientationModule = require("nativescript-screen-orientation");
var fs = require("file-system");
var webViewInterfaceModule = require('nativescript-webview-interface');
var oWebViewInterface;
var page;
function pageLoaded(){
setupWebViewInterface(page);
// orientationModule.setCurrentOrientation("landscape", function(){
// //console.log("landscape orientation set");
// });
}
// Initializes plugin with a webView
function setupWebViewInterface(page){
var webView = page.getViewById('webView');
var documents = fs.knownFolders;
oWebViewInterface = new webViewInterfaceModule.WebViewInterface(webView, documents.currentApp().path + '/htllo/index.html');
}
function navigatingTo(args) {
page = args.object;
page.bindingContext = createViewModel();
}
exports.pageLoad = pageLoaded;
exports.navigatingTo = navigatingTo;
回答1:
Here is an example how to add WebView src
from local file. In the example has been shown the both cases with nativescript-webview-interface
plugin and without it. ~/
returns the path to your app
folder.
main-page.xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="onLoaded">
<GridLayout rows="150 *" columns="*">
<WebView row="0" col="0" id="WebViewId"/>
<WebView row="1" col="0" id="WebViewId2"/>
</GridLayout>
</Page>
main-page.ts
import { EventData } from 'data/observable';
import { Page } from 'ui/page';
import { HelloWorldModel } from './main-view-model';
var webViewInterfaceModule = require("nativescript-webview-interface");
import {WebView} from "ui/web-view";
var oWebViewInterface;
export function onLoaded(args: EventData) {
let page = <Page>args.object;
var webView:WebView = <WebView>page.getViewById('WebViewId');
oWebViewInterface = new webViewInterfaceModule.WebViewInterface(webView, '~/index.html');
var SecondWebView:WebView = <WebView>page.getViewById('WebViewId2');
SecondWebView.src="~/secondpage.html"
page.bindingContext = new HelloWorldModel();
}
来源:https://stackoverflow.com/questions/39994187/how-to-load-files-into-webview-in-native-script