How to indent in newly added script tag

I am using the following code to insert a new script with contents into an HTML file. Currently the following code is working and a new script is inserted after the first existing script, the problem is that the content is not indented

eg. this is the output of the newly added script (as you can see it on one line)

<script> var keyOfFilesArray = Object.keys(data)[0]; var filesArray = data[keyOfFilesArray]; </script> 

I want to change it to indent, for example:

  • the second added open script tag will be inserted into the line after the closing tag of the first script
  • vars should be inserted one by one to be like this
 <script> var keyOfFilesArray = Object.keys(data)[0]; var filesArray = data[keyOfFilesArray]; </script> 

How can i do this? I believe that I need to add / n, but I'm not sure where it is best to paste it ...

https://jsfiddle.net/k32ntkr8/

This is JS code

 btn.onclick = function(e){ debugger; var innerhtml = [ ' var keyOfFilesArray = Object.keys(data)[0];', ' var filesArray = data[keyOfFilesArray]; ' ].join(''); var html = process(input.defaultValue,innerhtml); output.value = html; } function process(html,innerhtml) { var escapedHTML = html .replace(/body/g, 'body$') .replace(/head/g, 'head$'); sandbox.innerHTML = escapedHTML; var script = sandbox.querySelectorAll('#app-ux-bootstrap')[0]; var newScript = document.createElement('script'); newScript.innerText = innerhtml; script.parentNode.insertBefore(newScript, script.nextSibling); var unescapedHTML = sandbox.innerHTML .replace(/body\$/g, 'body') .replace(/head\$/g, 'head') .replace(/&quot;/g, "'"); return ( '<!DOCTYPE HTML>\n<html>' + unescapedHTML + '</html>' ); }; 

How can I do that? suggest, the answer below does not help much ... if I can improve this question, please let me know.

+4
source share
2 answers

Well, if you change the onclick handler to this

 btn.onclick = function(e){ debugger; var innerhtml = [ '', ' <script>', ' var keyOfFilesArray = Object.keys(data)[0];', ' var filesArray = data[keyOfFilesArray]; ', ' <\/script>' ].join('\n'); var html = process(input.defaultValue,innerhtml); output.value = html; } 

And change the process lines that populate the script with this

  var script = sandbox.querySelectorAll('#app-ux-bootstrap')[0]; script.parentNode.insertAdjacentHTML('afterBegin', innerhtml); 

You should get this conclusion

 <head> <script> var keyOfFilesArray = Object.keys(data)[0]; var filesArray = data[keyOfFilesArray]; </script> ... </head> 
+1
source

Something like that?

 var innerhtml = [ '\tvar keyOfFilesArray = Object.keys(data)[0];', '\tvar filesArray = data[keyOfFilesArray];' ].join("\n"); var script_code = '<script>\n' + innerhtml + '\n<\/script>'; 

Then just insert the script_code variable wherever you want it to appear on the page.

https://jsfiddle.net/e72c17zg/1/

+1
source

Source: https://habr.com/ru/post/1245915/


All Articles