获取nativescript中的webview内容

时间:2016-11-16 18:21:52

标签: webview nativescript

有没有办法在页面加载后阅读webview的内容?

原因是重定向(如window.location.replace或window.location.href)在我的情况下在IOS中不起作用,在Android中运行良好。

https://docs.nativescript.org/cookbook/ui/web-view 我可以访问网址,错误。但如何访问内容?

纳拉

2 个答案:

答案 0 :(得分:3)

我只是在寻找IOS。我找到了答案并在此分享。对于Android,我想指出一些线索。

if (webView.ios) {
    var webHeader = webView.ios.stringByEvaluatingJavaScriptFromString("document.head.innerHTML").trim();
    console.log(webHeader);

    var webBody = webView.ios.stringByEvaluatingJavaScriptFromString("document.body.innerHTML").trim();
    console.log(webBody);

} else if (webView.android) {
    webTitle = webView.android.getTitle(); //getting the title title
    console.log(webTitle)
}

Some stack overflow lead for Android

答案 1 :(得分:0)

您可以看一下这篇文章。安装一个库,该库允许通过可观察对象与Web视图进行通信。现在我自己使用它,它对于iOS和Android都非常有用

1-安装: tns插件添加nativescript-webview-interface 2-在Web项目中复制插件文件 cp node_modules / nativescript-webview-interface / www / nativescript-webview-interface.js app / www / lib / 3码: xml:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" 
loaded="pageLoaded">
<web-view id="webView"></web-view>
</Page>
var webViewInterfaceModule = require('nativescript-webview- 
interface');
var oWebViewInterface;

function pageLoaded(args){
page = args.object;
setupWebViewInterface(page) 
}

function setupWebViewInterface(page){
var webView = page.getViewById('webView');
oWebViewInterface = new 
webViewInterfaceModule.WebViewInterface(webView, '~/www/index.html');
}

function handleEventFromWebView(){
oWebViewInterface.on('anyEvent', function(eventData){
    // perform action on event
});
}

function emitEventToWebView(){
    oWebViewInterface.emit('anyEvent', eventData);
}

function callJSFunction(){
    oWebViewInterface.callJSFunction('functionName', args, function(result){

    });
}

网络视图:

<html>
<head></head>
<body>
    <script src="path/to/nativescript-webview-interface.js"></script> 
    <script src="path/to/your-custom-script.js"></script>        
</body>

网络视图js:

    var oWebViewInterface = window.nsWebViewInterface;

// register listener for any event from native app
oWebViewInterface.on('anyEvent', function(eventData){

});

// emit event to native app
oWebViewInterface.emit('anyEvent', eventData);

// function which can be called by native app
window.functionCalledByNative = function(arg1, arg2){
    // do any processing
    return dataOrPromise;
}

更多信息:

相关问题