滄海一幻覺
2021-11-25 16:08:02
我得到字符串:'<script class="heyo">document.write("hello")<\/script>' 我必須用 VanillaJS 創建一個內聯腳本元素。有沒有辦法觸發腳本執行?有效但太復雜:const scriptString = '<script class="heyo">document.write("hello")<\/script>';document.body.insertAdjacentHTML('beforeend', scriptString);const pseudoScript = document.body.querySelector('.heyo');const newScriptEl = document.createElement('script');[...pseudoScript.attributes].forEach(attr => { newScriptEl.setAttribute(attr.nodeName, attr.nodeValue);});newScriptEl.innerHTML = pseudoScript.text;document.body.append(newScriptEl);pseudoScript.remove();任何更好的想法表示贊賞。
2 回答
慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
我會說這或多或少是最好的方法。它“復雜”有什么關系?
我唯一沒有改變的不是將原始腳本插入到“實時”頁面中,而是插入到一個單獨的元素中,這也有不硬編碼類名的優點:
const scriptString = '<script class="heyo">document.write("hello")<\/script>';
const tempDiv = document.createElement("div");
tempDiv.innerHtml = scriptString;
const pseudoScript = tempDiv.firstChild;
const newScriptEl = document.createElement('script');
// ...
四季花海
TA貢獻1811條經驗 獲得超5個贊
一個小解決方案,appendChild而不是insertAdjacentHTML:
var scriptElement = document.createElement("script");
var scriptCode = document.createTextNode("document.write('hello')");
scriptElement.appendChild(scriptCode);
document.body.appendChild(scriptElement);
添加回答
舉報
0/150
提交
取消
