[Question] Add script using drag and drop that will add elements dynamically
Hey. Thank you for this great project. I'm using it in one of my project and need some help.
1- I have a block element with script in it. This script add a form dynamically inside a iframe.
blockManager.add('custom-script', {
label: 'email-custom-script',
category: 'Forms',
content: `
<div>
<script type="text/javascript" src="https://app.getresponse.com/view_webform_v2.js?u=zqQFS&webforms_id=SGRbz"></script>
<div>`,
attributes: {
title: 'Get Response Form',
class: 'fa fa-square'
}
})
When I drag and drop the script in anywhere on the page. Grapesjs ignore the position and render the form at the end of the page.

But when I export the HTML and CSS from grapesjs the position is correct where it should be. Why this is happening.

2- When I enable "allowScripts: 1," in grapesjs init function. I can add scripts but can't drag and drop (use) my custom block elements
let blockManager = editor.BlockManager;
let snippets = await this.getSectionSnippets();
snippets.map((item) => {
blockManager.add(item.name, {
label: item.name,
category: 'Sections',
content: `<html><head><script></script><style>${item.css}</style></head><body>${item.html}</body></html>`,
attributes: {
title: item.name,
class: 'fa fa-square'
}
})
});```
If a disable "allowScript" then I can use my custom block element but can't add scripts.
Hi! did you try putting your script in the script tag? this way it will be executed at the end and probably will respect the order you desire:
editor.BlockManager.add('form-block', {
script: function(){/* your-js */}
}
cheers.
When I drag and drop the script in anywhere on the page. Grapesjs ignore the position and render the form at the end of the page.
To be honest I don't know, it's all depended by the third-party library (in your case GetResponse) and how it appends content once loaded
When I enable "allowScripts: 1," in grapesjs init function. I can add scripts but can't drag and drop (use) my custom block elements
First of all, there is no need to use html, head, body tags in your blocks. You're dropping HTML snippets inside a body of already defined document...
I highly suggest you read about Components as you'll get much more control than simple blocks
Hi @artf thank you for your reply. The problem with the block element is solved. You were right there is no need to put html, head, body tags again.
But the problem with scripts is still there. I check the grapesjs logs. According to logs it is because of "Invalid target position. Target collection not found".

Any help will be appreciated. Thank you
Finally it is solved @pouyamiralayi Thank you for helping me out. After using your solution. It insert the script at correct position.