继上一篇《React Native WebView onMessage 收不到 window.postMessage 消息》之后,我遇到一个奇怪的 WebView 问题:
Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined.
这次就机智了,第一时间找 React Native 官网的 issues,果然就有了:onMessage failing when there are JS warnings and errors on the page
由于里面给的方案是这样的:
(function() {
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
})();
实际上,就是在上一篇中,我们复写了 window.postMessage
方法导致的。不过,由于上面的代码及作者给出的,都不能满足 AirBnb ESLint 的风格,因此便记录一下修改后的代码
const patchPostMessageFunction = () => {
const originalPostMessage = window.postMessage;
const patchedPostMessage = (message, targetOrigin, transfer) => {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = () => String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
window.postMessage = patchedPostMessage;
};
const patchPostMessageJsCode = `(${String(patchPostMessageFunction)})();`;
围观我的Github Idea墙, 也许,你会遇到心仪的项目