I have a backend API which provides some javascript code in the head_script and body_script keys. For example:
{
"head_script": "<script>console.log('abc1')</script><script>console.log('abc2')</script><script>console.log('abc3')</script><script>console.log(abc4')</script>",
"body_script": "<noscript><iframe src='.......'></iframe></noscript>"
}
What i tried to load those script in the head tag is the following and same for body tag also.
document.head.innerHTML = document.head.innerHTML + scripts['head_script']
I inspected html and saw that those appended in the head and body tags but found no impact of code.
Your suggestion will be appreciable. Thanks.
Already described in the previous section
2
Answers
Using
innerHTML
, the scripts are not automatically executed. This is because it does not trigger the browser’s built-in script execution mechanism.However, you may execute a script in page by creating and appending
<script>
tag in document.For this, you need to parse
head_script
orbody_script
, collect all scripts and execute the code between<script>...</script>
tags with above method.You can do this by following these steps:
Create a script element
Then add your custom code inside it
Finally you should append it to body
In your case you can extract all script code that receive from API with Regex. And Append each one to body for execution.