android - 在反应本机ios webview的所有iframe中注入javascript
问题描述
我正在使用react-native-webview
加载具有多个 iframe 的 URL。我正在使用该injectedJavaScript
方法将javascript注入加载的网站。代码仅注入顶部框架而不注入 iframe。
对于 android,我重写了public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
拦截我的 HTML 并将所需的 Javascript 添加到其中的方法。
对于 iOS,经过一些谷歌搜索后,我发现一些结果指向设置forMainFrameOnly
为 NO。我完全是 Objective C 的菜鸟,完全不知道如何设置它。我查看了 RNCWKWenView.m 文件,该文件forMainFrameOnly:YES
位于 2 个位置。我用 NO 替换了 YES,然后在 xcode 中重建了我的 iOS 项目。但仍然无法在 iframe 中获取我的 javascript。
重现: App.js 文件
import React, { Component } from 'react';
import { BackHandler, Platform } from 'react-native';
import { WebView } from 'react-native-webview';
const WEBVIEW_REF = 'webview';
export default class App extends Component {
webView = {
canGoBack: false,
ref: null
}
onAndroidBackPress = () => {
if (this.webView.canGoBack) {
this.refs[WEBVIEW_REF].goBack();
return true;
}
return false;
}
/**
* generate the javascript needed to be embedded inside the react native code.
*/
generateJSCode() {
var jsCode = "console.log('my script shows');";
return jsCode;
}
componentDidMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.onAndroidBackPress);
}
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress');
}
}
render() {
const uri = "http://localhost:8000";
return (
<WebView
ref={WEBVIEW_REF}
source={{uri}}
useWebkit={true}
injectedJavaScript={this.generateJSCode()}
javaScriptEnabled={true}
onNavigationStateChange={(navState) => { this.webView.canGoBack = navState.canGoBack; }}
/>
);
}
}
HTML 文件:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>this is a sample page</h1>
<iframe src="https://wikipedia.org/" style="width:100%;min-height: 400px;"></iframe>
<iframe src="https://wikipedia.org/" style="width:100%;min-height: 400px;"></iframe>
</body>
</html>
预期行为:
在 iOS 上:当我设置forMainFrameOnly:YES
为forMainFrameOnly:NO
时,我希望脚本也能注入到我的 iframe 中。
环境: - 操作系统:MacOS - 操作系统版本:- react-native 版本:0.60.5 - react-native-webview 版本:6.9.0
解决方案
推荐阅读
- ios - 如何使用 Swift 在我的项目中使用内部 JSON?
- javascript - 如何使用来自 javascript 数组的名称标签创建单选按钮列表
- r - 我怎么知道日期是星期几
- excel - 在功能区菜单中按下按钮的宏
- algorithm - 无法创建 cudnn 句柄:CUDNN STATUS INTERNAL ERROR
- python - 如何从 Pandas 的系列中获取包含行索引的列表
- html - Bootstrap 4,全宽行的内容
- assembly - 以 16 位实模式打印字符串
- android-tv - Exoplayer 2.0 上的 Widevine DRM 内容
- javascript - 如何将动态文本字段 sub_total 值自动汇总到总文本字段中