You will learn
- Common cross-domain technologies are introduced
- PostMessage implements cross-domain communication
- How to implement chatbots
- Node sets up a local server to render pages and cross domains
- Answer corpus design ideas
Results the preview
The body of the
1. Introduction to common cross-domain technologies
The first thing to emphasize is that cross-domain security restrictions are for the browser side; there are no cross-domain security restrictions for the server side. Our common cross-domain technologies mainly include the following:
- The json cross-domain
- The iframe + domain cross-domain
- Nginx reverse proxy cross-domain
- Cors cross-domain
- PostMessage cross-domain
JSONP implements cross-domain requests by dynamically creating script tags and then using the SRC of the script to obtain data across domains without the same origin policy. JSONP consists mainly of callback functions and data. The name of the callback function is typically specified in the request. The data is the JSON data passed into the callback function. We can generally define a callback function globally and pass it in the script tag:
window.handleData = function(data){
// ...
}
let script = document.createElement("script");
script.src = "https://xxxx.com/v0/search?q=xuxi&callback=handleData";
document.body.insertBefore(script, document.body.firstChild);
Copy the code
This allows us to retrieve the data returned by the server interface in the handleData callback function.
Although jSONP has a simple cross-domain approach, it only supports GET requests and has certain limits on the amount of data that can be transferred. Cors cross-domain is the local debugging method that we use most at present. The principle is to set the access-control-allow-Origin field of the response header on the server, so that the browser can detect the access-control-allow-Origin in the header. So you can cross domains.
As for the problem of two requests in the network after we set CORS, in fact, it involves the cross-domain request precheck of CORS, which is divided into two types: simple request and non-simple request. This knowledge can be separated into a separate article, and those who are interested can learn about it by themselves.
2. PostMessage implements cross-domain communication
The window.postMessage() method enables safe cross-source communication. Typically, scripts for two different pages can communicate with each other only if the page executing them is on the same protocol, port number, and host (the module document.domain of both pages is set to the same value). The window.postMessage() method provides a controlled mechanism to circumvent this restriction, and as long as used correctly, this method is safe.
In essence, postMessage() is based on the message event mechanism to achieve cross-domain communication. It belongs to the message form itself, such as window and the window embedded in the frame window. The basic form is as follows:
someWindow.postMessage(message, targetOrigin, [transfer]);
Copy the code
Parameter description:
- A reference to the someWindow window, such as the contentWindow property of the iframe, the window object returned by executing window.open, or the named or numerically indexed window.frames
- Message Specifies the data to be sent to other Windows. Does this mean that you can safely transfer data objects to the target window without having to serialize them yourself
- TargetOrigin specifies which Windows can receive message events through the origin property of the window. The value can be the string “*” (meaning unlimited). Not providing precise targets can lead to security issues such as data breaches
- Transfer is a string of Transferable objects that are passed along with message. Ownership of these objects will be transferred to the recipient of the message, and the sender will no longer retain ownership
We can listen for messages in the following ways:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
let origin = event.origin || event.originalEvent.origin;
if(origin ! = ="http://aaa:8080")
return;
// ...
console.log(event.data)
}
// The page for distributing messages
winB.postMessage(_({text: 'Take a break'}), origin)
Copy the code
Our events have the following core properties:
- Data is an object passed from another window
- Origin the origin of the message sender window when postMessage is called. The string is a combination of protocol, ://, domain name, and: port number
- Source a reference to the window object from which the message was sent; You can use this to establish two-way communication between two Windows that have different Origins
3. Implement the chatbot
With that in mind, let’s write a demo of our chatbot. First, we write two HTML pages, a.HTML and B.HTML, and then use Node to proxy two different pages with different ports:
// a.js
// rely on an HTTP module equivalent to import in Java and using in C#
var http = require('http');
var fs = require('fs');
var { resolve } = require('path');
// Create a server object
server = http.createServer(function (req, res) {
// Set the MIME of the response header to plain text when the request succeeds
res.writeHeader(200, {"Content-Type": "text/html"});
// Output characters to the client
let data = fs.readFileSync(resolve(__dirname, './a.html'))
res.end(data);
});
// Let the server listen for local port 8000 to start running
server.listen(8000.'127.0.0.1');
console.log('http://127.0.0.1:8000')
// b.js
// ...
server.listen(8001.'127.0.0.1');
Copy the code
As can be seen from the above, our A.HTML agent is on port 8000, and our B.TML agent is on port 8001. It can be seen from the same origin policy of the browser that they have cross-domain problems.
After the cross-domain implementation, we can start to build the page hierarchy. Here, we embed page B into page A in the form of iframe. The specific structure is as follows:
Firstly, we send the message to page B through the send button and input box on page A. The general structure is as follows:
<body>
<div class="wrap">
<iframe src="http://127.0.0.1:8001" frameborder="0" id="b"></iframe>
<div class="control">
<input type="text" placeholder="Please enter content" id="ipt">
<span id="send">send</span>
</div>
</div>
<script>
window.onload = function() {
let origin = 'http://127.0.0.1:8001';
let _ = (data) = > JSON.stringify(data);
let winB = document.querySelector('#b').contentWindow;
let sendBtn = document.querySelector('#send');
sendBtn.addEventListener('click', (e) => {
let text = document.querySelector('#ipt');
winB.postMessage(_({text: text.value}), origin)
text.value = ' ';
}, false)
winB.postMessage(_({text: ' '}), origin)
}
</script>
</body>
Copy the code
We can get a reference to b’s page form via the contentWindow of the iframe, and then trigger postMessage to send the data to B in the click event of the send button. B Page structure is as follows:
<body>
<div class="content">
<h4>Lab Intelligent robot</h4>
<div class="content-inner"></div>
</div>
<script>
/ / the corpus
const pool = [];
window.addEventListener("message", receiveMessage, false);
let content = document.querySelector('.content-inner');
let initContentH = content.scrollHeight;
let _ = (data) = > JSON.stringify(data);
function createChat(type, mes) {
let dialog = document.createElement('div');
dialog.className = type === 0 ? 'dialog robot' : 'dialog user';
let content = type === 0 ? `
<span class="tx">${type === 0 ? 'lab' : 'user'}</span>
<span class="mes">${mes}</span>
` : `
<span class="mes">${mes}</span>
<span class="tx">${type === 0 ? 'lab' : 'user'}</span>
`;
dialog.innerHTML = content;
return dialog
}
function scrollTop(el, h) {
if(el.scrollHeight ! == h) { el.scrollTop = h +100; }}function receiveMessage(event){
// Compatible with other browsers
let origin = event.origin || event.originalEvent.origin;
if(origin === 'http://127.0.0.1:8000') {
let data = JSON.parse(event.data);
if(data && ! data.text) { mes = {text: 'Hello, this is Robot Lab, how may I help you? ' };
event.source.postMessage(_(mes), event.origin)
content.appendChild(createChat(0, mes.text))
}else {
content.appendChild(createChat(1, data.text))
scrollTop(content, initContentH)
setTimeout((a)= > {
content.appendChild(createChat(0.'Working on it'))
scrollTop(content, initContentH)
}, 2000); }}}</script>
</body>
Copy the code
We analyze the data on page A in page B and make corresponding answers. And here we have our basic chatbot.
4. Answer corpus design ideas
As for how to parse and answer a message sent by page A, there are several ideas as follows:
- Through the back-end interface, that is, we can pass the data of A to a back-end interface as parameters, so that the back-end can return the required data, which is widely used in AI robots.
- Pure front-end implementation. The front end defines a corpus of responses that are obtained through keyword matching, which is typically used to answer common preset questions.
5. Pluggable
Pluggable means that one page can be used on different platforms. In this way, we can set the Origin whitelist and only need to encapsulate B page. Other systems can use the way similar to A page and only provide the interface for sending information, so that we can use it in different planes.
GitHub
The last
If you want to learn more about webpack, node, gulp, CSS3, javascript, nodeJS, Canvas and other front-end knowledge and actual practice, welcome to join us in the public account “Interesting Talk front-end” to learn and discuss, and jointly explore the boundary of the front-end.
More recommended
- “Front-end combat summary” of the variable promotion, function declaration promotion and variable scope detailed explanation
- “Front-end combat summary” how to change the URL without refreshing the page
- Front-end component/library packaging sharp Rollup use and configuration combat
- A picture shows you how to play vue-Cli3 quickly
- Vue Advanced Advanced series – Play with Vue and vuex in typescript
- Learn es6+ new features and es6 core grammar check quickly
- Implementing a CMS full stack project from 0 to 1 based on nodeJS (Part 1)
- Implementing a CMS full stack project from 0 to 1 based on nodeJS (middle)
- Implement a CMS full stack project from 0 to 1 based on nodeJS (Part 2)
- Implement server startup details for a CMS full stack project from 0 to 1 based on nodeJS
- Developing travel List with Angular8 and Baidu Maps API
- “Javascript advanced programming” core knowledge summary
- With CSS3 to achieve stunning interviewers background that background animation (advanced source)
- Write a mock data server using nodeJS in 5 minutes
- Teach you to use 200 lines of code to write a love bean spell H5 small game (with source code)