I have a Chatbot component in my Next.js app and I want anyone to use to as a chatbot in their website using <script tag. Suppose I put component in my public folder to have public access.
How can I implement this kind of functionality so that anyone can add this link in the script tag of their application and have access to my Chatbot
<script type="module" src="https://my-app-url/Chatbot.js" defer></script>
3
Answers
The simplest way would be to use an
iframe
.You can host your Next.js app with a page that only contains the chatbot component and set the background color as transparent.
Then, anyone with access to your app can use an
iframe
to embed the chatbot in their own website. Addingallowtransparency="true"
will achieve your desired effect.more info on iframe allowtransparency.
To create the iframe with javascript:
You should build the component, create HTML template and share the CDN Link
Host the HTML file (
ChatbotTemplate.html
) and the built JavaScript file (Chatbot.build.js
) on a server or CDN accessible to others.— HTML Template
Users can then include the following script tag in their HTML file to embed the chatbot:
Building a single react component with create-react-app
Step 1: initiate a new react project with
create-react-app
run
npx create-react-app chatbot-component
Step 2: configure the project to build a single component.
Remove everything except
public/index.html
andsrc/index.js
Your folder structure should look like this:
Delete everything in
index.html
, and replace everything inindex.js
with this:Step 3: run build
run
npm run build
to build the project.You should see this in you build folder:
The
main.{hash}.js
is what you want, you can rename it and host it on a cdn. Any HTML page with this script should see<h1>Hello world</h1>
in their body.Here’s an example of the build result.