Last active
May 3, 2018 14:45
-
-
Save 1fabiopereira/c950dfbb4433585589936184ae7037fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
let promiseChain = Promise.resolve(); | |
const promises = {}; | |
const callbacks = {}; | |
const init = () => { | |
// Gera o uuid da msg | |
const guid = () => { | |
const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); | |
return String(s4()).concat(String(s4()), "-", String(s4()), "-", String(s4()), "-", String(s4()), "-", String(s4()), String(s4()), String(s4())); | |
}; | |
window.webViewBridge = { | |
// Envia uma mensagem para o lado do React-Native | |
send (targetFunc, data = {}, success = () => {}, error = () => {}) { | |
const msgObj = { | |
targetFunc, | |
data, | |
msgId: guid(), | |
}; | |
var msg = JSON.stringify(msgObj); | |
promiseChain = promiseChain.then(() => new Promise((resolve, reject) => { | |
console.log('sending message ' + msgObj.targetFunc); | |
promises[msgObj.msgId] = { resolve: resolve, reject: reject }; | |
callbacks[msgObj.msgId] = { | |
onsuccess: success, | |
onerror: error | |
}; | |
window.postMessage(msg); | |
})).catch((e) => { | |
console.error('webViewBridge send failed ' + e.message); | |
}); | |
} | |
}; | |
// Recebe mensagem do React-Native | |
window.document.addEventListener('message', (e) => { | |
console.log('message received from react native'); | |
let message; | |
try { | |
message = JSON.parse(e.data); | |
} catch (err) { | |
console.error("failed to parse message from react-native".concat(err)); | |
return; | |
} | |
// Resolve promise - e envia a proxima mensagem se disponível | |
if (promises[message.msgId]) { | |
promises[message.msgId].resolve(); | |
delete promises[message.msgId]; | |
} | |
// Gatilho para o callback | |
if (message.args && callbacks[message.msgId]) { | |
if (message.isSuccessfull) { | |
try { | |
callbacks[message.msgId].onsuccess.apply(null, message.args); | |
} catch (err) {}; | |
} else { | |
try { | |
callbacks[message.msgId].onerror.apply(null, message.args); | |
} catch (err) {}; | |
} | |
delete callbacks[message.msgId]; | |
} | |
// Executa funções internas | |
if (message.action && message.payload) { | |
if (Object.prototype.hasOwnProperty.call(actionMap, message.action)) { | |
try { | |
actionMap[message.action](message.payload); | |
} catch (err) {}; | |
} | |
} | |
}); | |
}; | |
init(); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment