Last active
June 22, 2018 18:04
-
-
Save reggie3/53afa3b360baf4425a83e94087ec4c7c to your computer and use it in GitHub Desktop.
Webview sendMessage function
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
<Map | |
style={{ | |
width: '100%', | |
backgroundColor: 'lightblue' | |
}} | |
... | |
// handling a react-leaflet map click event | |
onClick={(event) => { | |
this.onMapEvent('onMapClicked', { | |
coords: [event.latlng.lat, event.latlng.lng] | |
}); | |
}} | |
... | |
/> | |
// An event has occured in the react-leaflet map rendered by the webpage | |
onMapEvent = (event, payload) => { | |
// build a default payload consisting of map information if one is not provided | |
if (!payload) { | |
payload = { | |
center: this.mapRef.current.leafletElement.getCenter(), | |
bounds: this.mapRef.current.leafletElement.getBounds(), | |
zoom: this.mapRef.current.leafletElement.getZoom() | |
}; | |
} | |
this.sendMessage({ | |
event, | |
payload | |
}); | |
}; | |
// data to send is an object containing key value pairs that will be | |
// spread into the destination's state or seen as an event | |
sendMessage = (payload) => { | |
const message = JSON.stringify({ | |
prefix: MESSAGE_PREFIX, | |
payload: payload | |
}); | |
if (document.hasOwnProperty('postMessage')) { | |
document.postMessage(message, '*'); | |
} else if (window.hasOwnProperty('postMessage')) { | |
window.postMessage(message, '*'); | |
} else { | |
console.log('unable to find postMessage'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment