Issue #2069Opened June 6, 2019by Sparragus0 reactions

[BUG] `allowScripts: true` still deletes <script> tags

Question

Hi all. Thanks for creating and maintaining this amazing project. 🙏

Bug Description

I have a block that inserts a script as specified here: https://grapesjs.com/docs/modules/Components-js.html#basic-scripts

When I drag the block to the canvas, the component will indeed have the script attached to itself. However, when I reload the page, the script is no longer there.

I've seen multiple issues where this is discussed, and they all seem to be resolve by adding

const editor = grapesjs.init({
	...
	allowScripts: 1,
});

Examples: https://github.com/artf/grapesjs/issues/1123 https://github.com/artf/grapesjs/issues/837 https://github.com/artf/grapesjs/issues/721

However, allowScripts: 1 doesn't seem to be working for me.

Expected

I expect the <script> to still be there because allowScript: 1.

Reproducible Case

Here's a CodeSandbox where the bug can be reproduced: https://codesandbox.io/s/compassionate-gagarin-dclo5

Steps to reproduce:

  1. Drag a "Button" block to the canvas.
  2. Click the button. It displays an alert.
  3. You can see the code for the script if you open the modal where the code is shown.
  4. Reload the page.
  5. Click the button again, no alert is shown.
  6. Go see the code, and the <script> will no longer be there.

Here's a short video of me reproducing these steps: https://www.youtube.com/watch?v=g4fes1nU5h0

I hope this is enough information. If more is needed, I'll be happy to provide it.

Thank you. Cheers!

Answers (3)

dosponsorJune 13, 20190 reactions

Can you please provide the solution for this issue.

artfJune 14, 20190 reactions

Thanks for the report @Sparragus The problem here is when you use a function for the script inside Blocks. When the editor tries to store the JSON the structure is serialized but the function is not serializable so for that component an empty script string is stored.

I know that is what we indicate in the documentation but we used blocks only to show quick examples, actually, you should always create a custom component for the one with a script.

editor.DomComponents.addType('foo-button', {
	model: {
		defaults: {
			tagName: "button",
		    name: "Button",
		    content: "Button",
		    script: function() {
		      this.addEventListener("click", () => {
		        alert("Meow");
		      });
		    }
		}
	}
})
editor.BlockManager.add("button", {
  label: "Button",
  content: { type: 'foo-button' }
});
SparragusJune 24, 20190 reactions

@artf Thank you for the clarification. Cheers.

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.