GrapeJS - A guide to saving and loading your unique page design

I successfully built a basic page builder using the GrapeJS Docs and it is functioning smoothly. I believe that adding two functions to save and load the created page would enhance its capabilities. How can I implement this?

const editor = grapesjs.init({
  // Specify where to initialize the editor. You can also provide an HTMLElement instead
  container: '#gjs',
  // Retrieve the canvas content directly from the element
  // Alternatively, we could use: `components: '<h1>Hello World Component!</h1>'`,
  fromElement: true,
  // Editor size
  height: '300px',
  width: 'auto',
  // Temporarily disable the storage manager
  storageManager: false,
  // Remove all default panels
  panels: { defaults: [] },
  blockManager: { },
  layerManager: { },
  deviceManager: { },
  selectorManager: { },
  styleManager: { },
  storageManager: { }
});

Answer №1

1.In order to retrieve project source data after the initialization, Grapes js offers two useful functions.

editor.getProjectData(); // obtain project data
editor.loadProjectData(jsonProjectData); // load project data

2.Additionally, Grapes js provides 3 functions for accessing HTML, CSS, and JS code.

editor.getHtml();
editor.getCss();
editor.getJs();

3.If you wish to set up a storage manager, follow the example below and use editor.store() to save and editor.load() to load project data from specified endpoints.

const editor = grapesjs.init({
  ...
  storageManager: {
    type: 'remote',
    stepsBeforeSave: 3,
    options: {
      remote: {
        urlLoad: `http://localhost:3000/projects/${projectID}`, // Send GET request to fetch the data
        urlStore: `http://localhost:3000/projects/${projectID}`, // Submit POST request to save the data
        fetchOptions: opts => (opts.method === 'POST' ?  { method: 'PATCH' } : {}),
                onStore: (projectData, editor) => {
                    return {
                        gjs_html: editor.getHtml(),
                        gjs_css: editor.getCss(),
                        gjs_js: editor.getJs(),
                        gjs_source: projectData,
                    };
                },
        onLoad: result => result.data,
      }
    }
  }
});

If you want more information about the storage manager, refer to the official documentation here.

Answer №2

  1. Store current template stage

             let components = editor.getComponents();
             let style = editor.getStyle()
             let templateData = {
                 components: components,
                 style: style
             };
             localStorage.setItem("template", JSON.stringify(templateData));
    
  2. Retrieve saved information

             let templateData = JSON.parse(localStorage.getItem("template"));
             editor.setComponents(templateData.components);
             editor.setStyle(templateData.style);
    

You have the option to save in a database instead of using localStorage. This method has proven effective for me!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issues arising from an array in need of a function to retrieve data from Firestore

My current task involves developing a method that can read an array of elements (objects) from firestore: I've set up a service to fetch the data from firestore, starting with retrieving an array of document references var data = snapshot.get(&apos ...

Executing functions in real-time using React Native

I'm fairly new to Object-Oriented Programming (OOP) and my understanding of promises, asynchronous/synchronous function execution is quite basic. Any guidance or help from your end would be greatly appreciated! Let's take a look at an example fr ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Using .setAttribute within a for-loop in JavaScript does not function as intended

I have encountered a minor issue with my JS-Script. I attempted to assign each element in an array a unique number, and these numbers were stored in another array. Initially, everything worked perfectly outside of the for-loop. var i = 0; document.getElem ...

The Angular controller is defined in a separate file such that the controller file is loaded before the Module file

I have made progress in the following areas: I successfully created a module using the correct convention: var myApp = angular.module('myApp', []);. I ensured to include the empty array as the second parameter. In addition, I developed some con ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Flickering Page Load Issue in iOS App Built with PhoneGap

My PhoneGap application utilizes slide in and slide out animations that are created entirely with CSS animations. You can check out the project that inspired my app here. In the demo, you'll notice that the slide transitions are smooth. However, whe ...

Exploring the power of Vue.js: Leveraging the onChange feature with TomSelect

How can I implement onChange with TomSelect in my code? <TomSelect :disabled="disableForm" v-model="wareHouse.agent.id" :onChange="changeAgentData" class="w-full&qu ...

Issue encountered while attempting to execute express through node

Currently, I am attempting to initiate a basic server on my Mac in order to access a file from localhost. My server file consists of the following code with Node and Express installed: var express = require('express'), app = express(); app.use ...

The ideal login page design

I apologize for my lack of knowledge in React, but I am quite new to it and have been struggling with this issue for days. I am having trouble creating a login page in ReactJS. Here is the code in my app.js: import React from 'react'; import {Ha ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

Issue with Vue mounting causing component to not receive updated values

Below is the Vue main file I'm working with: export default { name: 'app', components: { FormSelector, }, data () { return { headerInfo: { issue: '', mode ...

Navigating through NodeJS-

Summary: After calling the code below once with no issues, I encountered an error the next time I ran it. To resolve the error, I had to restart the server every time after encountering it, but even then, the code only worked once. NOTE: I decided to use ...

Adjust the scroll position when the window is resized

Currently, I am using a combination of smooth scroll and IDs/anchor tags to navigate through the content on my website. The code snippet below is designed to fetch the ID of the next 'section' in the DOM and assign it as the href for the 'vi ...

Chrome is blocking the loading of a local image in THREE.js due to cross-origin restrictions

While working with THREE.js, I encountered an issue in the developer console: Cross-origin image load denied by Cross-Origin Resource Sharing policy. This error only occurs when I try to run my script in Chrome. The code snippet in question is as follows ...

Having trouble capturing the 'notificationclick' event in the service worker when using Firebase messaging with Nuxt.js and Vue.js?

Experiencing difficulties in detecting events other than install, activate, or push in my firebase-messaging-sw.js. Notifications are being received and displayed, but I am unable to detect the event handler for notificationclick. When a firebase notificat ...

What is the best way to add an additional selected option after the page has been loaded?

I'm currently having trouble adding an extra option to a Chosen after the page has loaded completely. It works fine when I add values before the page loads, but once it's fully loaded, I can't seem to add values to the chosen component, as s ...

The content displayed on body.innerHTML does not match the information found in the page source code

Why is the page source newer than the document.body.innerHTML, and how does this happen? While watching a video on YouTube and inspecting the page source in Chrome's console, I noticed that YouTube assigns a unique signature to all videos. Here are t ...

Word with the Most Points

I have created a code to determine the highest scoring word as a string, however when I calculate all words and attempt to display the results, I am encountering an issue where all results are showing as: NaN function high(x) { var words = x.split(&ap ...