Home >Web Front-end >JS Tutorial >Sharing of two-way cross-domain plug-ins implemented in JavaScript_javascript skills
Due to browser (same-origin policy) restrictions, JavaScript cross-domain issues have always been a rather thorny issue. HTML5 provides the function of cross-document message transmission to receive and send information to each other between web documents. Using this function, not only web pages with the same origin (domain port number) can communicate with each other, but also cross-domain communication can be achieved between two different domain names.
Cross-document messaging Cross Document Messaging provides the postMessage method to transfer data between different web documents and supports real-time messaging. Many browsers will now support this feature, such as Google Chrome 2.0, Internet Explorer 8.0, Firefox 3.0, Opera 9.6, Safari 4.0, etc.
So, what should I do if browsers such as IE6 and IE7 do not support HTML5?
You can use the window.name method, because the modification of window.name does not involve cross-domain issues. Although it is not particularly ideal to use, the effect is acceptable.
However, we can't always write window.postMessage, window.addEventListener, window.name, etc. every time it involves cross-domain.
To this end, I abstracted the entire cross-domain process and encapsulated it into a JavaScript plug-in to solve the two-way cross-domain problem, realize real-time communication between different web page documents, and achieve cross-domain communication between two different domain names. .
Demo download address: http://xiazai.jb51.net/201501/other/jcrossdomain_v2.rar, version v2
javascript cross-domain plug-in jcrossdomain.js
var jcd = {
initParent: function(callback, iframeId){
_jcd.init(callback, document.getElementById(iframeId).contentWindow);
},
initChild : function(callback){
_jcd.init(callback, win.parent);
},
sendMessage: function(data){
_jcd.msg(data);
}
};
win.jCrossDomain = jcd;
})(window);
Call method in parent webpage:
//Initialization, loading callback function and iframe id
jCrossDomain.initParent(cb, 'iframeA');
//Send a message
jCrossDomain.sendMessage('hello, child');
Call method in sub-webpage:
//Initialization, loading callback function
jCrossDomain.initChild(cb);
//Send a message
jCrossDomain.sendMessage('hello, parent');
Simulation test tips:
In order to achieve communication between different domains, you can add two domain names to the hosts file of the operating system for simulation.
Add two different domain names to the hosts file
127.0.0.1 parent.com
127.0.0.1 child.com
The evolution process of programmers: