我有一个用Expo构建的React Native应用程序。在How can I add links in a Highcharts tooltip that will open on mobile's browser?上,我可以将URL传递给Highcharts,以便在单击工具提示时打开该URL:
return(
<View style={styles.container}>
<ChartView
onMessage={m => this.onMessage(m)}
config={config}
/>
</View>
这触发此方法打开URL:
onMessage = (m) => {
let data = JSON.parse(m.nativeEvent.data);
Linking.openURL(data.url)
};
然后通过全局变量window.myURL
填充URL,并使用postMessage()
发送消息:
render() {
let Highcharts = "Highcharts";
let config ={
...
plotOptions: {
series: {
stickyTracking: false,
point: {
events: {
click: function(e) {
window.postMessage(JSON.stringify({'url': window.myUrl}));
}
}
}
},
},
tooltip: {
useHTML: true,
formatter: function () {
window.myUrl = extras.url;
return `<div class="text">some text</div>`;
}
};
这在iOS(物理和仿真器)上都运行良好,但在Android(物理和仿真器上)均无效。
我经历了不同的Github问题,例如onMessage not called in native code even though sent from webview( android)和react native html postMessage can not reach to WebView,他们倾向于建议在window.postMessage()
上使用一些超时。但是,我发现即使这样也不起作用:
plotOptions: {
series: {
point: {
events: {
click: function(e) {
setTimeout(function() {
console.log('bla');
window.postMessage(JSON.stringify({'url': window.myUrl}));
}, 200);
}
}
}
},
},
由于即使console.log()
无法正常工作,在我看来click
事件也未被Android捕获。
如何让Android知道此事件,以便我可以查看消息然后打开URL?
答案 0 :(得分:3)
"click"
事件很好。问题是,RN核心的<WebView>
Android版实现在填充window.postMessage()
方面存在缺陷。 this github issue中对此问题进行了充分的讨论。
所以问题的本质似乎是,RN由于某种原因不得不填充本地window.postMessage
,但是覆盖操作没有及时进行,导致仍然window.postMessage
调用本地
该github问题中提出的一种解决方案(适用于Android)只是停止使用本机window.postMessage
,而直接使用内部接口,这是实际的polyfill函数。
// in place of `window.postMessage(data)`, use:
window.__REACT_WEB_VIEW_BRIDGE.postMessage(String(data))
请注意,此API不是公开的,将来可能会更改。