我需要在 WebView 上捕获点击(单击)事件(以在 SVG 文件中显示图片),以便我可以根据单击图像的位置显示另一个 Nativescript 页面(或显示另一个 SVG)。
有没有办法用 WebView 的 x,y 坐标捕获点击事件?
另一件事。我发现 WebView 可以捕获加载的 html 中的超链接......有没有办法在 html 中创建一个链接,以便它在 nativescript 应用程序中打开另一个本地文件?例如:这里,但没有用(东西在我的“app”文件夹下)但我收到了 404。
最佳答案
这是一个可能的解决方案。
向 WebView 中显示的页面添加一些前端 Javascript 代码。使用该 Javascript 检测页面上的点击,点击时将 WebView 重定向到新的(假)页面。在 NativeScript 方面,听听 loadStartedEvent
的 WebView(在 WebView 导航时触发)并在 WebView 尝试导航到新的假页面时执行某些操作。
我看起来像这样:
在浏览器/WebView 代码中。我们为 click
添加一个事件监听器事件(您可能希望将其更改为 tap
事件)。单击后,将用户导航至 nativescript://{X coordinate}/{Y coordinate}
.
window.addEventListener('click', function(event){
window.location.href='nativescript://' + event.screenX + '/' + event.screenY;
})
然后在 NativeScript 端,设置一个事件监听器,监听 WebView 何时导航,如果它导航到以“nativescript://”开头的 URL,则停止加载事件并从 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])
}
});
至于加载本地文件,你只需要创建一个
file://
本地文件的路径。例如。var linkPath = fs.path.join(fs.knownFolders.currentApp().path, 'localHTMLFiles') + '/myFile.html';
var link = '<a href="file://" + linkPath + ">"'
关于Nativescript WebView 捕获 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294845/