首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将自定义JavaScript注入到React Native的Webview中

将自定义JavaScript注入到React Native的Webview中
EN

Stack Overflow用户
提问于 2018-09-29 22:13:14
回答 1查看 5.8K关注 0票数 2

我想把javascript代码注入到react原生web视图的injectedJavaScript方法中。我可以注入一段javascript代码,但是多段代码不能正常工作。有什么技巧可以做到吗?

代码语言:javascript
运行
复制
  injectedJavaScript={`document.querySelector('.header-wrapper').style.display='none' ` }

这是可行的。

但是我想要像这样的东西注入多个javasript东西,但不能工作。

代码语言:javascript
运行
复制
let  jsCode = `(
               function() {

                document.querySelector('.footer').style.display='none' ;
                document.querySelector('.tabs').style.display='none' ;
                document.querySelector('.header-wrapper').style.display='none' ;
                document.querySelector('.wrapper').style.margin-top=-70px ;

              })();`;

  render() {
    return (
      <WebView
      source={{uri: 'blabla.com'}}
        style={{marginTop: 20}}
        injectJavaScript={jsCode}
        javaScriptEnabledAndroid={true}
      />
    );
  }

当我尝试这样做时,我得到了意想不到的标记等。我如何注入多个javascripts来反应本机web视图?提前谢谢。

完整代码:

代码语言:javascript
运行
复制
import React from 'react';
import { StyleSheet, Text, View,WebView } from 'react-native';

export default class App extends React.Component {





  render() {

  return (
      <WebView
      source={{uri: 'https://trends.google.com/trends/trendingsearches/daily?geo=TR'}}
      injectedJavaScript={`document.querySelector('.trending-searches-footer').style.display='none';`
      + ` document.querySelector('.content-header-buttons daily-header-buttons').style.display='none'; `
       + `  document.querySelector('.trending-feed-tabs').style.display='none'; `
      + ` document.querySelector('.header-wrapper').style.display='none'; `
      + ` document.querySelector('.trending-feed-page-wrapper').style.marginTop='-70px'; `
      }
      javaScriptEnabled={true}
          ref="WEBVIEW_REF"
      />
    );
  }

}
EN

回答 1

Stack Overflow用户

发布于 2018-09-30 04:56:12

您的javascript中有一个错误,这将导致脚本失败:

代码语言:javascript
运行
复制
document.querySelector('.wrapper').style.margin-top=-70px; // this is wrong syntax

尝尝这个

代码语言:javascript
运行
复制
document.querySelector('.wrapper').style.marginTop='-70px';

要在injectedJavascript中使用它,请像编写一行代码一样编写脚本,这没有任何区别,但您应该确保您的javascript没有任何错误:

代码语言:javascript
运行
复制
let  jsCode = `
    document.querySelector('.footer').style.display='none';
    document.querySelector('.tabs').style.display='none';
    document.querySelector('.header-wrapper').style.display='none';
    document.querySelector('.wrapper').style.marginTop='-70px';
 `;

并且使用injectedJavaScript而不是injectJavaScript来使用它。

代码语言:javascript
运行
复制
<WebView
  source={{uri: 'blabla.com'}}
  style={{marginTop: 20}}
  injectedJavaScript={jsCode}
  javaScriptEnabledAndroid={true}
/>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52569195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档