在 WebView 源代码中执行 JavaScript [英] Execute JavaScript inside WebView source

查看:45
本文介绍了在 WebView 源代码中执行 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何(如果可能的话)在 React Native 的 WebView 中内部"执行 JS?

Anyone knows how (if possible) to execute JS "inside" a WebView in React Native?

场景:我在我的 WebView 中显示了这个远程登录页面(网站),并且这个网站有一系列与用户活动相对应的事件.所有事件都会触发一个回调,WebView 必须侦听该回调(不是问题).
在每个回调中都有一个对 JavaScript 函数的引用,该函数必须在 WebView 中调用(这就是问题所在!).
因此,从我的 React Native 应用程序中,我需要调用这个 JavaScript 函数,该函数放置在我的 WebView 中加载的网站页面(源代码)上.

The scenario: I have this remote logon page (website) displayed in my WebView, and this website has a sequence of events that happens corresponding to the user activity. All events fire one callback each, which the WebView must listen on (not an issue).
Within each callback there is a reference to a JavaScript function, that must be called inside the WebView (that's the issue!).
So from my React Native app, I need to call this JavaScript function, that's placed on the website page (source) that's loaded in my WebView.

我有什么:我用 onShouldStartLoadWithRequest 并使用此操作 WebView 的行为,效果很好.
关于 JavaScript 执行,我尝试了 getWebViewHandle 方法,但没有做到,至少在我的座位上没有.
我也查看了 injectedJavaScript 属性,但问题是我不知道在触发回调之前要执行什么 JavaScript.

What I have: I listen for the callbacks with onShouldStartLoadWithRequest and manipulate the behaviour of the WebView with this and it works great.
Regarding JavaScript execution I have tried the method getWebViewHandle but that didn't do it, at least not from my seat.
I looked at injectedJavaScript property too, but the problem is that I don't know what JavaScript to execute before the callbacks are fired.

有人知道如何解决这个问题吗?

Anyone knows how to solve this?

推荐答案

2018 年 11 月更新

Webview 组件现在支持 injectJavaScriptinjectedJavaScript 道具.

Webview component now supports injectJavaScript and injectedJavaScript props.

示例:

<WebView
  source={{ uri: 'https://github.com/facebook/react-native' }}
  injectedJavaScript="window.alert('first message')"
  injectJavaScript={() => {
    return "window.alert('second message')";
  }}
/>

原答案

使用 iOS 和 Android 原生组件可以在 Webview 中调用 javascript 方法.但是目前 react-native 不提供 JavaScript 执行所需的 API.您可以在 this github issue 中查看讨论.

Calling javascript methods inside a Webview is possible with iOS and Android native components. But required API for javascript execution is currently not provided by react-native. You can see the discussion in this github issue.

但是,有一个 第 3 方模块 提供双向通信您的应用程序和 Webview 之间.将一些本机代码集成到您的项目中后,您就可以开始使用它了.

However, there is a 3rd party module that's providing bi-directional communication between your app and a Webview. You can start using it after integrating some native code into your project.

这篇关于在 WebView 源代码中执行 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆