Executing [removed] elements inserted with [removed]

后端 未结 20 2521
囚心锁ツ
囚心锁ツ 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:02

    Try this snippet:

    function stripAndExecuteScript(text) {
        var scripts = '';
        var cleaned = text.replace(/]*>([\s\S]*?)<\/script>/gi, function(){
            scripts += arguments[1] + '\n';
            return '';
        });
    
        if (window.execScript){
            window.execScript(scripts);
        } else {
            var head = document.getElementsByTagName('head')[0];
            var scriptElement = document.createElement('script');
            scriptElement.setAttribute('type', 'text/javascript');
            scriptElement.innerText = scripts;
            head.appendChild(scriptElement);
            head.removeChild(scriptElement);
        }
        return cleaned;
    };
    
    
    var scriptString = 'alert(\'test\');test';
    document.getElementById('element').innerHTML = stripAndExecuteScript(scriptString);
    

提交回复
热议问题