ドメイン間通信のいくつかの方式(jsonp,hash,postMessage,websocket,cors)
5758 ワード
<html>
<head>
<meta charset="utf-8">
<title> title>
head>
<body>
<script type="text/javascript">
// ajax【 】https://segmentfault.com/a/1190000006669043
// jsonp.js
script>
<script src="http://www.abc.com/?data=name&callback=jsonp" charset="utf-8">script>
<script type="text/javascript">
// jsonp({
// data: {
//
// },
// });
script>
<script type="text/javascript">
/**
*
*/
// jsonp , jsonp.js
// hash, A iframe frame B
// A :
var B = document.getElementsByTagName('iframe');
B.src = B.src + '#' + 'data';
// B
window.onhashchange = function () {
var data = window.location.hash;
};
// postMessage
// A(http:A.com) B(http:B.com)
Bwindow.postMessage('data', 'http://B.com');
// B
Awindow.addEventListener('message', function (event) {
console.log(event.origin);
console.log(event.source);
console.log(event.data);
}, false);
// Websocket【 】http://www.ruanyifeng.com/blog/2017/05/websocket.html
var ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = function (evt) {
console.log('Connection open ...');
ws.send('Hello WebSockets!');
};
ws.onmessage = function (evt) {
console.log('Received Message: ', evt.data);
ws.close();
};
ws.onclose = function (evt) {
console.log('Connection closed.');
};
// CORS【 】http://www.ruanyifeng.com/blog/2016/04/cors.html
// url( ),options( )
fetch('/some/url/', {
method: 'get',
}).then(function (response) {
}).catch(function (err) {
// , then ,
});
script>
body>
html>