get content of webview in nativescript

2020-05-03 12:19发布

Is there a way I can read the content of webview after the page is loaded ?

The reason is redirect (like window.location.replace or window.location.href ) is not working in IOS in my case, works fine in Android.

https://docs.nativescript.org/cookbook/ui/web-view I can access url, error. but how to access content ?

Narayan

2条回答
Explosion°爆炸
2楼-- · 2020-05-03 12:50

I was only looking for IOS. I found the answer and sharing it here. For Android I would like to point some leads.

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

查看更多
霸刀☆藐视天下
3楼-- · 2020-05-03 12:55

You could look at this post. installs a library that allows communication with the webview through observables. Right now I'm using it myself and it's great for both iOS and Android

1- install: tns plugin add nativescript-webview-interface 2- in web project copy plugin file cp node_modules/nativescript-webview-interface/www/nativescript-webview-interface.js app/www/lib/ 3- code: 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){

    });
}

web-view:

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

web-view 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;
}

More Info:

查看更多
登录 后发表回答