Sometimes you encounter silly requirements, such as front-end single sign-in! When you encounter a need, you have to think of a solution.
Here I will give you a simple front-end single sign-in solution.
What is used is postMessage cross-domain information transmission and onstorage monitoring.
The knowledge points used in this article are koa setting up static resource services, cross-domain, postMessage usage, onstorage monitoring storage
The first step is to set up two services with different ports.We use koa2 here to build two services to different ports to simulate the cross-domain situation that needs to occur in real work.
It is very simple and mainly uses the koa-static middleware.
It is also very easy to build. If you want to learn node-related knowledge, you can add me on WeChat shouzi_1994 or leave your contact information below the blog. I won’t go into too much nonsense here. Just go to the code video and there will be detailed building steps.
// localhost:4000const Koa = require('koa'); const path = require('path')const static = require('koa-static')const app = new Koa();//Set the path of static resources const staticPath = './static'app.use(static( path.join( __dirname, staticPath) )) console.log (service starts on port 4000) app.listen(4000);// localhost:3000const Koa = require('koa'); const path = require('path') const static = require('koa-static' )const app = new Koa();//Set the path of static resources const staticPath = './static'app.use(static( path.join( __dirname, staticPath) )) console.log (service starts on port 4000) app.listen(4000);The second step, cross-domain communication postMessage
Let’s first take a look at the postMessage API
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
A reference to another window, such as the contentWindow property of an iframe, the window object returned by executing window.open, or named or numerically indexed window.frames.
message
Data to be sent to other windows. It will be serialized by the structured cloning algorithm. This means that you can safely transfer data objects to the target window without any restrictions without serializing them yourself. [1]
targetOrigin
Specify which windows can receive message events through the origin attribute of the window. Its value can be a string (indicating unlimited) or a URI. When sending a message, if any of the protocol, host address or port of the target window does not match the value provided by targetOrigin, the message will not be sent; only if the three completely match, the message will be sent. This mechanism is used to control which windows messages can be sent to; for example, when using postMessage to transmit a password, this parameter is particularly important, and its value must be ensured to be exactly the same as the origin attribute of the intended recipient of the message containing the password. to prevent passwords from being intercepted by malicious third parties. If you know exactly which window the message should be sent to, always provide a targetOrigin with an exact value instead. Failure to provide the exact target will result in data leakage to any malicious site interested in the data.
transfer optional
It is a string of Transferable objects delivered at the same time as the message. The ownership of these objects will be transferred to the receiver of the message, and the sender will no longer retain ownership.
Is it easy to understand how it works? Let me explain it in Chinese.
The (parent) child window to be transferred. postMessage (transmitted content, which address to transfer to, [whether permissions are transferred (generally not used)]);
Let me tell you in advance that if you want to transfer across domains, it must be a parent-child page, that is, a page through js Open, or a page nested in iframe.
Okay, let's start writing code
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width, initial-scale=1.0> <meta http-equiv=X-UA -Compatible content=ie=edge> <title>Document</title></head><body> <!-- postMessage and iframe solve common cross-domain problems--> I am the content of the port 3000 website <button onclick=send()>Send a message to my son</button> <iframe style=display:none src=http://localhost:4000 frameborder=0></iframe><script> function send() { window.frames[0].postMessage({a:1},http://localhost:4000); // Trigger the message event of cross-domain subpages} window.addEventListener('message', function(event) { console.info('My son wrote a letter', event); }, false);</script></body></html>
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width, initial-scale=1.0> <meta http-equiv=X-UA -Compatible content=ie=edge> <title>Document</title></head><body> <!-- postMessage and iframe solve common cross-domain problems--> I am the content of the port 4000 website <button onclick=send()>Send a message to dad</button> <iframe style=display:none src=http://localhost:4000 frameborder=0></iframe><script> window.addEventListener(message,function(event){ console.log(Dad wrote:, event) },false) function send() { parent.postMessage({a:1}, 'http://localhost:3000'); // }</script></body></html>
At this point, we have implemented cross-domain communication between parent and child pages, but this communication only occurs within one window and does not achieve the effect I want. What should I do?
Monitor value changes and respond promptlyAt this point everyone needs to think about what can be seen by all websites with the same domain name on the browser?
That's right, storage, we just need to monitor this.
Here we choose to listen to localStorage and now we make improvements to the subpages
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width, initial-scale=1.0> <meta http-equiv=X-UA -Compatible content=ie=edge> <title>Document</title></head><body> <!-- postMessage and iframe solve common cross-domain problems--> I am the content of the port 4000 website <button onclick=send()>Send a message to dad</button> <iframe style=display:none src=http://localhost:4000 frameborder=0></iframe><script> window.addEventListener(message,function(event){ console.log(Dad wrote:, event) var data = JSON.stringify(event.data) window.localStorage.setItem(data,data) },false) window.onstorage(function(st){ console.log(st.key,st.value) }) function send() { parent.postMessage({a:1 }, 'http://localhost:3000'); // }</script></body></html>
Look, are we now able to respond to content transmitted across domains?
thinkNow that we have achieved cross-domain communication between two pages, how to do three or more cross-domain communication? In fact, there is a truth. Now that I’ve told you the truth, go and experience the writing method yourself.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.