injectJavaScript在Webview中不起作用本机

时间:2017-10-11 14:03:12

标签: javascript android react-native webview

我无法将这个简单的js代码注入到反应原生的webview中。

I referred this link also but no solution provided here.

Then I found this one which works for html props but not uri.

import React, { Component } from 'react';
import { Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component<{}> {

  injectjs(){

    let jsCode = 'alert(hello)';
    return jsCode;
  }

  render() {
    return <WebView 
    javaScriptEnabled={true}
    injectedJavaScript={this.injectjs()} 
    source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }} />;
  }
}

6 个答案:

答案 0 :(得分:5)

嗯,这里有多个问题。第一个是您的Web视图需要包含在包含Flex的包含View组件中:1。第二,injectJavascript只接受字符串 - 而不是函数。第三,似乎你试图在没有定义它的情况下使用hello作为变量,或者如果它是一个字符串,那么你的语法必须是这样的:injectJavascript = {'alert(“hello”)'}。此外,当视图加载时,injectJavascript已被触发,因此如果您打算这样做,那么您就会很好。你可以在网页视图开始加载时注入javascript,使用道具,onLoadStart和injectJavascript的组合,但实现是完全不同的,所以这是一个不同的问题。试试这段代码:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component {

  render() {
    let yourAlert = 'alert("hello")'
    return (
     <View style={{flex: 1}}>
       <WebView
        javaScriptEnabled={true}
        domStorageEnabled={true}
        injectedJavaScript={yourAlert}
        source={{ uri: "https://www.google.com" }} style={{ marginTop: 20  }} />
    </View>
   )
  }
}

答案 1 :(得分:4)

您需要添加 onMessage 道具。

enter image description here

答案 2 :(得分:2)

我也遇到了这个问题,我可以通过设置mixedContentMode来实现它:

<强> mixedContentMode = { '兼容性'}

请参阅下面的props.url = {uri:'https://google.com'}快速测试javascript粘贴“看着我,我正在注入”搜索框。

import React from 'react';
import { Button, StyleSheet, Text, View, ScrollView, WebView } from 'react-native';

export class WebViewController extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        const url = this.props.url;
        console.log(`v:1`);
        console.log(`url info: ${JSON.stringify(url)}`);
        console.log(`javascript: ${Constants.javascript.injection}`);
        return (
            <View style={styles.root}>
                <WebView
                    source={url}
                    injectedJavaScript={Constants.javascript.injection}
                    mixedContentMode={'compatibility'}
                    javaScriptEnabled={true}
                    style={styles.webview}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    root: {
        flex:1,
        alignSelf: 'stretch',
    },
    webview: {
        flex:1,
        alignSelf: 'stretch',
    },
})

const Constants = {
    javascript: {
        injection: `
            Array.from(document.getElementsByTagName('input')).forEach((item) => {
                if(item.type == "search") {
                    item.value = "look at me, I'm injecting";
                }
            })
        `
    }
}

我希望问题是当您直接添加html并注入javascript时webview将注入视为来自同一来源的javascript。与通过URL加载页面时不同,您的javascript是外来的,并且通过默认值mixedContentMode被认为是在原点之外,这是'never'

请参阅:https://facebook.github.io/react-native/docs/webview.html#mixedcontentmode

mixedContentMode 指定混合内容模式。即WebView将允许安全的来源加载来自任何其他来源的内容。

mixedContentMode的可能值为:

'never'(默认值) - WebView不允许安全来源从不安全的来源加载内容。 'always' - WebView将允许安全的来源加载来自任何其他来源的内容,即使该来源不安全。 '兼容性' - WebView将尝试与混合内容的现代Web浏览器方法兼容。

答案 3 :(得分:2)

添加onMessage方法确实有效。

import React, { Component } from 'react';
import { Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component<{}> {
  render() {
    return 
      <WebView 
        javaScriptEnabled={true}
        injectedJavaScript={'alert("hello")'} 
        source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }}
        onMessage={(event) => {
          console.log('event: ', event)
        }}
      />;
  }
}

答案 4 :(得分:0)

问题是因为Javascript代码需要在WebView完全加载后执行。

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component {

  injectjs() {

    let message = "Hello";

    let jsCode = `
      setTimeout(() => {
        alert('${message}');
      }, 1500)`;

    return jsCode;
  }

  render() {
    return <WebView
      javaScriptEnabled={true}
      injectedJavaScript={this.injectjs()}
      source={{ uri: "https://www.google.com" }} style={{ marginTop: 20 }} />;
  }
}

setTimeout完全加载后几秒钟,您可以使用WebView加载您的Javascript代码。

此外,我建议您使用``代替'',并将其他变量放入变量中。

示例

injectjs(){

    var message = "Hello";

    let jsCode = `alert('${message}')`;
    return jsCode;
}

答案 5 :(得分:0)

https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method

follow this link 

The injectJavaScript method

While convenient, the downside to the previously mentioned 
injectedJavaScript prop is that it only runs once. That's why we 
also expose a method on the webview ref called injectJavaScript 
(note the slightly different name!).
相关问题