我想从Google Maps API获取一些信息。我在googleMap.html
文件中编写了一个函数,并想返回值:
我的React的componentDidMount
:
componentDidMount() {
this.iFrameNode = ReactDOM.findDOMNode(this.refs.iframe);
this.iFrameNode.onload = () => {
const promise1 = new Promise(resolve => {
window.addEventListener('message', data => {
resolve(data);
});
const iFrameNode = ReactDOM.findDOMNode(this.refs.iframe);
iFrameNode.contentWindow.postMessage({}, '*');
});
promise1.then(value => {
console.log(`visibleMarkers: ${value}`);
});
};
},
Google映射iFrame代码:
function getVisibleMarkers(mapInstance, markers) {
const mapBounds = mapInstance.getBounds();
return markers.filter(marker => mapBounds.contains(marker.getPosition()));
}
function handlePostMessage(message) {
const visibleMarkers = getVisibleMarkers(window.googleMapsInstance, window.googleMapsMarkerInstance);
window.parent.postMessage(JSON.stringify(visibleMarkers), '*')
}
function initialize() {
window.addEventListener('message', handlePostMessage, false);
}
从父级到iFrame的发布消息正确运行,并且计算出的值正确。问题是window.parent
命令中的CORS。我收到此错误:
Uncaught DOMException: Blocked a frame with origin "https://static.parastorage.com" from accessing a cross-origin frame.
我在做什么错?我的网站与google-maps iFrame之间还有其他通信方式吗?