Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize a pluggable cross-domain chat robot

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to achieve a pluggable cross-domain chat robot". The explanation in this article is simple and clear and easy to learn and understand. let's go deep into the editor's train of thought. Let's study and learn "how to achieve a pluggable cross-domain chat robot"!

You will learn

Introduction of common schemes of cross-domain technology

Realizing Cross-domain Communication with postMessage

How to realize chat Robot

Node builds local servers to render pages and cross domains

Thoughts on the Design of answer Corpus

Effect preview

Text

1. Introduction of common schemes of cross-domain technology

First of all, it should be emphasized that cross-domain security restrictions are for the browser side, and there are no cross-domain security restrictions on the server side. The main cross-domain technologies we commonly use are as follows:

JSONP cross-domain

Iframe+domain cross-domain

Nginx reverse proxy cross-domain

Cors cross-domain

PostMessage cross-domain

The principle of JSONP to achieve cross-domain request is to dynamically create script tags, and then use the src of script to obtain data across domains without the constraints of the same origin policy. JSONP is mainly composed of callback function and data. The name of the callback function is usually specified in the request. The data is the JSON data passed into the callback function. Generally, we can define a callback function globally, and then pass the callback function into 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)

So we can get the data returned by the server interface in the callback function handleData.

Although the cross-domain implementation of jsonp is very simple, it only supports get requests and has a certain limit on the amount of data transferred. Cors cross-domain is a common local debugging method. The principle is to set the Access-Control-Allow-Origin field of the response header header on the server, so that the browser can detect the Access-Control-Allow-Origin in the header, so that it can cross-domain.

As for the problem of two requests in network after we set up cors, it actually involves the pre-checking of cross-domain requests in cors, which can be divided into simple requests and non-simple requests. This piece of knowledge can be extracted from an article separately, and those who are interested can learn about it by themselves.

2. PostMessage implements cross-domain communication

The window.postMessage () method can securely implement cross-source communication. In general, for scripts on two different pages, the two scripts can communicate with each other only if the pages executing them are located on the same protocol, port number, and host (the modulus Document.domain of both pages is set to the same value). The window.postMessage () method provides a controlled mechanism to circumvent this limitation, which is safe as long as it is used correctly.

Essentially, 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 of frame embedded in window. The basic usage is as follows:

SomeWindow.postMessage (message, targetOrigin, [transfer])

Parameter description:

A reference to a someWindow window, such as the contentWindow property of iframe, the window object returned by window.open, or a named or numerically indexed window.frames

The data that message will send to other window. It means that you can safely transfer the data object to the target window without having to serialize it yourself.

TargetOrigin uses the origin property of the window to specify which windows can receive message events, whose value can be the string "*" (for unlimited). Failure to provide an exact target will lead to security problems such as data disclosure

Transfer is a string of Transferable objects passed with message at the same time. Ownership of these objects will be transferred to the recipient of the message, while the sender will no longer retain ownership

We can monitor message 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 winB.postMessage that dispatches the message (_ ({text: 'rest'}), origin)

We have the following core attributes in our event:

Objects passed by data from other window

The origin of the message sender window when origin calls postMessage. This string is made up of protocol, ": /", domain name, and ": Port number".

Source's reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origin

3. Implementation of chat robot

After getting familiar with the above knowledge points, we began to write the demo of our chat robot. First, we write two html, a.html and b.html, and then use node to proxy two different pages and set different ports:

/ / a.js / / relies on a http module, equivalent to import in java, and using var http = require ('http') in C#; 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 res.writeHeader (200,{ "Content-Type": "text/html"}) when the request succeeds / / output the characters let data = fs.readFileSync (resolve (_ _ dirname,'. / a.html') res.end (data);}) to the client; / / Let the server listen on local port 8000 and start running server.listen (8000Ling 127.0.0.1'); console.log ('http://127.0.0.1:8000') / / b.js / /. Server.listen (8001 recording 127.0.0.1')

From the above, we can see that our a.html proxy is under port 8000 and the b.html agent is under port 8001. From the homology policy of the browser, we can see that they have cross-domain problems.

After the cross-domain implementation, we can start to build the page level. Here, we embed the b page into the a page in the form of iframe, with the following structure:

In this way, we can happily build postMessage system. First of all, we send the message to page b through the send button and input box on page a, which is roughly structured as follows:

Send _ 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)}

We can get a reference to the b-page form through iframe's contentWindow, and then trigger postMessage to send the data to B in the click event of the send button. The structure of the B page is as follows:

Lab Intelligent Robot / / 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? `${type = = 0? 'lab':' user'} ${mes} `:` ${mes} ${type = = 0? 'lab':' user'} `; dialog [XSS _ clean] = 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. 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 (() = > {content.appendChild (createChat (0, 'solving')) scrollTop (content, initContentH)}, 2000) }

We parse the data of page an in the b page and answer accordingly. In this way, our basic chat robot is realized.

4. Thoughts on the Design of answer Corpus

As for how the b page parses and answers when we send a message on page a, there are several ways of thinking:

Through the back-end interface, that is, we can pass the data of an as a parameter to a back-end interface, 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 the corpus of answers and gets the answers through keyword matching, which is generally used to answer common preset questions.

5. Achieve pluggable

Pluggable is a page that can be used on different platforms. This we can set up the origin whitelist, just need to encapsulate the b page, other systems can use a-page-like way, only provide the interface to send information, so that we can use it in different levels.

Thank you for your reading. the above is the content of "how to achieve pluggable cross-domain chatbots". After the study of this article, I believe you have a deeper understanding of how to achieve pluggable cross-domain chatbots. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report