skip to Main Content

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


  1. 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.

    const script = document.createElement("script");
    script.type = "text/javascript";
    script.appendChild(document.createTextNode(code));
    
    const parent = document.head; // or document.body;
    parent.appendChild(script);
    

    For this, you need to parse head_script or body_script, collect all scripts and execute the code between <script>...</script> tags with above method.

    Login or Signup to reply.
  2. You can do this by following these steps:

    Create a script element

    let scriptEle = document.createElement("script");
    

    Then add your custom code inside it

    scriptEle.text=`console.log('abc1')`;
    

    Finally you should append it to body

    document.body.appendChild(scriptEle);
    //or
    document.head.appendChild(scriptEle);
    

    In your case you can extract all script code that receive from API with Regex. And Append each one to body for execution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search