Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nativescript WebView capture onclick event

Tags:

nativescript

I need to capture tap (click) events on a WebView (to display a picture in a SVG file), so that I can show another Nativescript page (or show another SVG) based on where the image is clicked..

Is there a way to capture a tap event with x,y coordinates for WebView?

Another thing. I found WebView can capture hyperlinks within the html loaded... Is there a way to make a link within the html so it open another local file within the nativescript app? For example: < a href="~/stuff/foo2.html">here< /a >, but didn't work (where stuff is under my "app" folder) but I am getting a 404.

like image 735
jmak Avatar asked Feb 05 '23 20:02

jmak


1 Answers

Here's a possible solution.

Add some front end Javascript code to the page displaying in your WebView. Use that Javascript to detect taps on the page and when tapped redirect the WebView to a new (fake) page. On the NativeScript side, listen to the loadStartedEvent of the WebView (firing when the WebView navigates) and do something when the WebView tries to navigate to that new fake page.

I'd look something like this:

In the browser/WebView code. We add an event listener for click events (you probably want to change this to tap events). When clicked navigate the user to nativescript://{X coordinate}/{Y coordinate}.

window.addEventListener('click', function(event){
    window.location.href='nativescript://' + event.screenX + '/' + event.screenY;
})

Then on the NativeScript side, set up an event listener listening for when the WebView is navigating and if it's navigating to a URL starting with 'nativescript://' then stop the loading event and extract the coordinates from the URL.

var wv = new webViewModule.WebView();
wv.on(webViewModule.WebView.loadStartedEvent, function(event) {

    // Check if the WebView is trying to navigate to 'nativescript://...'
    if (event.url.indexOf('nativescript://') === 0 ) {
        // Stop the loading event
        if (ios) {
            event.object.ios.stopLoading();
        } else if (android) {
            event.object.android.stopLoading();
        }

        // Do something depending on the coordinates in the URL
        var coords = event.url.split('/');
        coords.splice(0, 2);
        console.log(coords[0] + ' - ' + coords[1])
    }
});

As for loading local file, you just need to create a file:// path to the local file. E.g.

var linkPath = fs.path.join(fs.knownFolders.currentApp().path, 'localHTMLFiles') + '/myFile.html';

var link = '<a href="file://" + linkPath + ">"'
like image 88
Emil Oberg Avatar answered Feb 08 '23 08:02

Emil Oberg