在React原生WebView中接收来自注入JavaScript的消息

在React原生WebView中接收来自注入JavaScript的消息,javascript,react-native,webview,Javascript,React Native,Webview,在我的React原生应用程序中,我使用WebView通过“injectedJavascript”道具显示谷歌广告(AdSense)。问题是我不能事先知道广告的高度。所以我首先给它一个随机高度,当它的样式更新时,我计划正确设置它的高度 我假设我必须在注入的JS代码中获取高度,然后使用“window.postMessage()”方法通过“onMessage”属性将其发送到WebView MutationObserver结合承诺似乎非常适合这种情况。现在,我只想接收来自webview的消息。这是我现在

在我的React原生应用程序中,我使用WebView通过“injectedJavascript”道具显示谷歌广告(AdSense)。问题是我不能事先知道广告的高度。所以我首先给它一个随机高度,当它的样式更新时,我计划正确设置它的高度

我假设我必须在注入的JS代码中获取高度,然后使用“window.postMessage()”方法通过“onMessage”属性将其发送到WebView

MutationObserver结合承诺似乎非常适合这种情况。现在,我只想接收来自webview的消息。这是我现在的代码,但没有发送任何消息:

export default class App extends Component {
constructor(props) {
    super(props);
}

_onMessage(e) {
    console.warn(e.nativeEvent.data);
}

render() {
    const jsCode = ` 
        window._googCsa('ads', pageOptions, adblock1);

        function waitForAdSense(id) {
            var config = {
                attributes: true,
                attributeFilter: ['style'],
            };

            return new Promise((resolve, reject) => {
            var adSenseElement = document.body.getElementById(id);
            if (adSenseElement.style) {
                resolve(adSenseElement.style.height);
                return;
            }
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                if (mutation.attributeName === 'style') {
                    observer.disconnect();
                    resolve(adSenseElement);
                    return;
                }
            });
        });
        observer.observe(adSenseElement, config);
    });
    }

    waitForAdSense('afscontainer1').then(height => {
    window.postMessage(height, '*');
    });
    `;
    return (
    <ScrollView>
        <WebView
        key={'AdSense'}
        ref={'webview2'}
        style={{ height: 300 }}
        source={{
            uri: isAndroid
            ? 'file:///android_asset/widget/adSense.html'
            : './widget/index.html',
        }}
        javaScriptEnabled={true}
        mixedContentMode="compatibility"
        injectedJavaScript={jsCode}
        scrollEnabled={false}
        domStorageEnabled={true}
        onMessage={this._onMessage}
        scalesPageToFit
        startInLoadingState={true}
        automaticallyAdjustContentInsets={false}
        />
        ;
    </ScrollView>
    );
}
}

你有什么想法吗?我想我的函数waitForAdSense()可能不知怎么被窃听了。提前谢谢

最好的解决方案是在React本地移动应用程序上使用AdMob而不是AdSense。由于AdSense javascript并没有考虑到这个用例,所以处理这些问题有点毫无意义。这是一个易于在应用程序中集成AdMob的工具。

我成功地将其与注入代码中的这些更改结合使用:

window._googCsa('ads', pageOptions, adblock1);

  function waitForAdSense() {
      var config = {
          attributes: true,
          attributeFilter: ["style"]
      };

      var adSenseContainer = document.getElementById("afscontainer1");

      return new Promise((resolve, reject) => {
          var observer = new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                  if (mutation.attributeName === 'style' && adSenseContainer.style.height) {
                      var height = adSenseContainer.style.height;
                      resolve(height);
                      observer.disconnect();
                      return;
                  };
              });
          });
          observer.observe(adSenseContainer, config);
      });
  };

    waitForAdSense().then(height => {
        window.postMessage(height, '*');
    });

谢谢你的建议

为什么使用AdSense而不是AdMob?这个特定的广告是一个iframe,需要在WebView中实现。然后,这个特定的广告可能需要使用移动标准在移动设备上实现
window._googCsa('ads', pageOptions, adblock1);

  function waitForAdSense() {
      var config = {
          attributes: true,
          attributeFilter: ["style"]
      };

      var adSenseContainer = document.getElementById("afscontainer1");

      return new Promise((resolve, reject) => {
          var observer = new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                  if (mutation.attributeName === 'style' && adSenseContainer.style.height) {
                      var height = adSenseContainer.style.height;
                      resolve(height);
                      observer.disconnect();
                      return;
                  };
              });
          });
          observer.observe(adSenseContainer, config);
      });
  };

    waitForAdSense().then(height => {
        window.postMessage(height, '*');
    });