簡體   English   中英

粘貼HTML代碼后執行Javascript腳本

[英]Executing Javascript scripts after pasting HTML code

我正在做一些實驗,發現在任何網頁上執行該代碼時:

document.documentElement.innerHTML = document.documentElement.innerHTML;

Javascript腳本只是被“禁用”。 因此,這是我編寫的一個小腳本,該腳本使用jQuery重新執行這些腳本(因此您需要在某些網站上注入jQuery(我正在使用Firebug + FireQuery)):

// Disabling all javascript scripts
document.documentElement.innerHTML = document.documentElement.innerHTML;

// Saving scripts tags and his parent
var scripts = [];
jQuery('html').find('script').each(function(){
    scripts.push([jQuery(this),jQuery(this).parent()]);
}).remove(); // REMOVING ALL SCRIPT TAGS

// Re-appending those deleted script tags in the right place
for (var i in scripts) {
    scripts[i][1].append(scripts[i][0]);
}

因此,此腳本可在我嘗試過的大多數網站上運行,但以下網站除外: Google (在Firefox中)

我實際上想做的事情是存儲Google HTML,並將其粘貼到iframe(通過Firefox Extension)。 因此,一切工作正常,除了我無法使Javascript腳本正常工作(沒有自動完成功能,按鈕不起作用...)。 這是我得到的錯誤:

gapi.loaded_0不是函數

window.google.pmc未定義

我當時在想,這可能是由於執行訂單問題或其他原因造成的。 但是我該如何解決。 還有其他方法可以重新運行Javascript腳本嗎? 還是做我在做的更好的方法?

謝謝 !

是! 有一種更好的方式來做您正在做的事情。

首先,發生了什么:

當您使用innerHTML ,現有元素將從DOM中刪除。 並不是完全“燒死地球”,因為其他引用可能仍然存在,但它們不在DOM中。

幸運的是,有一種簡單的方法可以解決此問題:

這是事件委托的精彩討論,描述了您需要執行的操作。 值得一讀以了解幕后知識。

了解這些內容后,請查看jQuery的Event Delgation ,它可以為您完成很多工作:

由於您沒有顯示任何HTML,因此我將提出一些建議:

<div id="contents-will-be-replaced">
  <button>Click me</button>
</div>


// Attach to the DIV
// But listen for buttons
$( "#contents-will-be-replaced" ).on( "click", "button", function() {
  alert("Button pushed");
});

U可以簡單地使用Jquery的.html()在dom中動態加載腳本。 基本上,jquery將在將html添加到DOM時對其進行檢查,然后自動在頭部創建一個腳本標簽。 非常漂亮。 看看是否適合您。

從文檔:

By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM