首页 > 解决方案 > 在反应本机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:YESforMainFrameOnly:NO时,我希望脚本也能注入到我的 iframe 中。

环境: - 操作系统:MacOS - 操作系统版本:- react-native 版本:0.60.5 - react-native-webview 版本:6.9.0

标签: androidiosreact-nativewkwebview

解决方案


推荐阅读