react-native - 如何获取 HTML 页面中 WebView 中发送的变量的值?
问题描述
我正在开发一个需要将变量发送到将在 WebView 中显示的 html 页面的应用程序。这是 React Native 应用程序代码的基本示例。
export default class App extends Component {
render()
{
let variableCadena="React Native";
return(
<Container>
<WebView
style={{flex: 1}}
originWhitelist={['*']}
source={{uri:'file:///android_asset/PaginaEjemplo.html'}}
style={{ marginTop: 20 }}
javaScriptEnabled={true}
domStorageEnabled={true}
allowFileAccess={true}
allowUniversalAccessFromFileURLs={true}
injectedJavaScript={variableCadena}
>
</WebView>
</Container>
);
}
};
HTML 可以像下面这样简单。
<html>
<head>
<title>Ejemplo de inyeccion desde React Native</title>
<script type="text/javascript">
var variable = variableCadena;
</script>
</head>
<body>
<script type="text/javascript">
document.body.innerHTML = "<h1>La variable es:"
+variable+ "</h1>"
</script>
</body>
</html>
预期的结果是网页在 h1 标记中显示应用程序中定义的 React Native 文本。谢谢大家的建议。
解决方案
首先,我希望您使用https://github.com/react-native-community/react-native-webview而不是来自 react-native 因为它现在已被弃用。
您可以使用该injectJavascript(...)
方法。像这样的东西...
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
export default class App extends Component {
render() {
const run = `
document.body.style.backgroundColor = 'blue';
true;
`;
setTimeout(() => {
this.webref.injectJavaScript(run);
}, 3000);
return (
<View style={{ flex: 1 }}>
<WebView
ref={r => (this.webref = r)}
source={{
uri: 'https://stackoverflow.com/questions/57065527',
}}
/>
</View>
);
}
}
这会给你这样的东西:
现在解决这个问题!查看零食:https ://snack.expo.io/@abranhe/stackoverflow-57065527
更新作者要求使用变量进行演示
应用程序.js
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
export default class App extends Component {
injectjs() {
let name = 'Abraham';
setTimeout(() => {});
return `document.getElementById('inject').innerHTML = '<h1>The name is <b>${name}</b></h1>'`;
}
render() {
return (
<View style={{ flex: 1 }}>
<WebView
ref={(r) => (this.webref = r)}
injectedJavaScript={this.injectjs()}
source={require('./demo.html')}
/>
</View>
);
}
}
演示.html
<html>
<head>
<title>Ejemplo de inyeccion desde React Native</title>
<style>
body {
background-color: aquamarine;
display: -webkit-flex;
-webkit-justify-content: center;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
</head>
<body>
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf" />
<div id="inject">
</body>
</html>
结果
推荐阅读
- c# - 如果使用自动化,部分输入字段不显示
- python - 有没有使用 CuGraph 找到 girvan newman 的方法?
- node.js - Node.js:如何对大 JSON 文件的对象一个一个处理以避免堆限制错误
- scala - 在 IntelliJ 中评估返回值的表达式
- javascript - Chrome 扩展中的 popup.js 未收到从 contentScript.js 发送的消息
- blazor - 如何在组件中填充渲染片段
- reactjs - 在 Reactjs 应用程序中创建用户时,Firebase 身份验证超时
- python - 从 pdf 文件导出表格
- frame - CSMA/CD 中的最小帧大小
- python - 在python中对包含字符串和数字的txt文件进行排序