【问题标题】:WebView onMessage giving unexpected responseWebView onMessage 给出意外响应
【发布时间】:2017-07-03 14:55:59
【问题描述】:

我正在尝试从 WebView 中获取一些数据并进入我的应用程序的 RN 层,但是我从 WebView 收到的响应看起来像一个事件对象,我无法在任何地方看到从 WebView 发送的字符串在物体上。

响应如下所示:

Proxy { dispatchConfig: Object, _targetInst: Constructor, isDefaultPrevented: function, isPropagationStopped: function, _dispatchListeners: function...}

单击上面的对象会导致奇怪的行为,并且结构会发生变化。点击打开后,上面的对象如下所示:

{
    [[Handler]]: Object,
    [[Target]]: SyntheticEvent,
    [[IsRevoked]]: false
}

在上面那个看起来很奇怪的事件对象中,我找不到我硬编码要发送回 RN 的字符串。

有什么想法吗?

这是我传递给 WebView 的代码:

var defer = function (fn, delay) {
  if (!fn || typeof fn !== 'function') return console.log('defer: First argument must be a function.');
  if (!delay) delay = 0;

  return setTimeout(fn, delay);
};

var initBridge = function () {
  try {
    if (!window.postMessage) {
      console.log('Could not initiate WebView bridge');
    }

    defer(function () { window.postMessage('HELLO'); }, 500);
    let sentTest = false
    document.addEventListener('message', function (data) {
      console.log('Received message from RN!');
      console.log(data);
    });

    console.log('WebView bridge successfully initialised');
  } catch (err) {
    console.log(window.postMessage);
    console.log('Failed to initiate WebView bridge');
    console.log('Error: ', err);
  }
};

defer(initBridge);

这是我的onMessage 处理程序:

  _onMessage (message) {
    console.log('MESSAGE FROM WEBVIEW: ', message)
    console.log('ARGS: ', arguments)

    this._webView.postMessage('Hello, from RN!')
  }

【问题讨论】:

    标签: react-native webview


    【解决方案1】:

    如果你在从 WebView 收到的消息上调用message.persist(),那么你可以在message.nativeEvent.data 下找到数据。

    【讨论】:

    • message.nativeEvent.data 为我解决了问题。需要先打电话message.persist()吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2021-09-29
    • 2018-09-15
    • 2021-09-27
    • 2018-05-16
    • 2014-09-21
    相关资源
    最近更新 更多