Executing [removed] elements inserted with [removed]

后端 未结 20 2862
囚心锁ツ
囚心锁ツ 2020-11-22 00:12

I\'ve got a script that inserts some content into an element using innerHTML.

The content could for example be:



        
20条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 01:09

    Try this, it works for me on Chrome, Safari & Firefox:

    var script = document.createElement('script');
    script.innerHTML = 'console.log("hi")';
    document.body.appendChild(script); 
    --> logs "hi"
    

    One thing to note though, is that the following div-nested script will NOT run:

    var script = document.createElement('div');
    script.innerHTML = '';
    document.body.appendChild(script);
    --> doesn't log anything
    

    For a script to run it has to be created as a node then appended as a child. You can even append a script inside a previously injected div & it will run (I've run into this before when trying to get ad server code to work):

    var div = document.createElement('div');
    div.id = 'test-id';
    document.body.appendChild(div);
    var script = document.createElement('script');
    script.innerHTML = 'console.log("hi")';
    document.getElementById('test-id').appendChild(script);
    --> logs "hi"
    

提交回复
热议问题