[英]Executing <script> injected by innerHTML after AJAX call
[英]Executing host script from an injected page
我正在編寫一個Safari擴展,它為我不擁有的網頁添加了一些功能。 我希望我注入的JavaScript頁面能夠激活主頁使用的一些JavaScript函數,但它不起作用。 在控制台上,我收到消息ReferenceError: Can't find variable: function_name
。
我的腳本被指定為結束腳本,因此應該加載整個頁面。 該函數也是從頁面上的onclick()
處理程序調用的,如下所示:
onclick="function_name($(this).up());"
我可以獲得對該頁面元素的引用,但是當我調用element.onclick()
我得到另一個錯誤: TypeError: 'undefined' is not a function (evaluating '$(this).up()')
。
奇怪的是,當我從AppleScript調用JavaScript函數do JavaScript "function_name()" in page
)時,它工作正常。 我該如何觸發這些功能?
它不起作用,因為擴展的注入腳本是沙盒; 除了DOM之外,它無法看到頁面的全局對象(反之亦然)。 解決此安全限制的一種方法是讓注入的腳本使用您需要的語句創建<script>
元素並將其插入到文檔中。 例如:
var myScriptElement = document.createElement('script');
myScriptElement.innerHTML = 'alert("Page is using jQuery " + $.fn.jquery)';
document.querySelector('head').appendChild(myScriptElement);
但是,插入的腳本也無法訪問注入的腳本的對象。 因此,例如,如果您嘗試從插入的腳本訪問擴展的safari
對象,您將收到引用錯誤。
我可以從canisbos擴展答案。 您可以使用PostMessage函數與插入的腳本進行通信。
注入腳本:
//insert script to page
var myScriptElement = document.createElement('script');
myScriptElement.innerHTML =
'window.addEventListener("message", function(e) {' +
' if (e.data.msg == "do") {' +
' foo(e.data.info);' +
' postMessage({msg: "done", info: "answer"}, "*");' +
' };' +
'}, false);'
document.querySelector('head').appendChild(myScriptElement);
//add answers listener
window.addEventListener('message', function(e) {
if (e.data.msg == 'done') {
console.log(e.data.info);
};
}, false);
//add the testing function on the body click
document.addEventListener('click', function (e) {
//call inserted script
postMessage({msg: 'do', info: 'from inject'}, '*');
}, false);
測試html頁面:
<html>
<script>
function foo(text) {
console.log(text);
};
</script>
<body>
<button id='button' onclick='foo("from page")'>test</button>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.