包含webview的React本机模块将其重写为库

时间:2019-04-07 08:07:46

标签: javascript android react-native webview exp

我有一个模块,其中包含一个webview,在其中必须注入一些javascript代码以从网页中检索信息。

下面的模块我想像一个库一样编写它,但是我对是否有可能存在疑问。

要调用该模块,我需要这样做:

import ResolveUrl from './ResolveUrl';

export default class App extends React.Component {
  componentDidMount() {
    this.resolveUrl
      .get('openload', 'https://oload.stream/embed/eGU2r6teA0c/')
      .then(url => {
        console.log(url);
      })
      .catch(err => alert('error: ' + err));
  }

  render = () => (
    <View>
      <ResolveUrl
        ref={r => (this.resolveUrl = r)}
        style={{ width: 0, height: 0, backgroundColor: '#000' }}
      />
    </View>
  );
}

我想从代码中删除此部分:

<ResolveUrl
            ref={r => (this.resolveUrl = r)}
            style={{ width: 0, height: 0, backgroundColor: '#000' }}
          />

代码模块:

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

export default class ResolveUrl extends Component {
  constructor() {
    super();
    this.state = {
      urlOpenload: '',
      code: '',
      isMounted: false,
    };
  }

  componentDidMount() {
    this.setState({ isMounted: true });
  }
  componentWillUnmount() {
    this.setState({ isMounted: false });
  }

  Openload(url) {
    return new Promise(async (resolve, reject) => {
      setTimeout(() => {
        if (this.state.isMounted) {
          this.setState({ urlOpenload: url });
          setInterval(() => {
            if (this.state.code != '')
              resolve('https://openload.co/stream' + this.state.code);
          }, 5000);
        }
      }, 1000);
    });
  }

  get(type, url) {
    type = type.toLowerCase();
    return new Promise(async (resolve, reject) => {
      switch (type) {
        case 'openload':
          resolve(this.Openload(url));
          break;
      }
    });
  }

  render() {
    const jsCodeOpenload = `
        (function ready() {
          function whenRNPostMessageReady(cb) {
            if (window.postMessage.length === 1) cb();
            else setTimeout(function() { whenRNPostMessageReady(cb) }, 100);
          }
          whenRNPostMessageReady(function() {
            window.postMessage(document.getElementById('lqEH1').innerHTML);
          });
        })();`;
    return (
      <View>
        {this.state.urlOpenload != '' && (
          <WebView
            source={{
              uri: this.state.urlOpenload,
            }}
            onMessage={evt => {
              alert(evt.nativeEvent.data)
              this.setState({ code: evt.nativeEvent.data });
            }}
            injectedJavaScript={jsCodeOpenload}
            javaScriptEnabled
            style={{ flex: 1 }}
          />
        )}
      </View>
    );
  }
}

0 个答案:

没有答案