[英]Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery
[英]Javascript: Call global function from within Self-Invoking Anonymous Function / Immediately-Invoked Function Expression (IIFE)
我正在尝试创建Chrome扩展程序。 我的内容脚本中具有以下功能来处理文件下载:
function handleDownloadFile(urlVal){
console.log("handleDownloadFile called");
}
然后,我有以下代码将函数注入DOM(从此处获取: https : //stackoverflow.com/a/11811558/3778854 ):
function injectScript(source) {
var elem = document.createElement("script"); //Create a new script element
elem.type = "text/javascript"; //It's javascript
elem.innerHTML = source; //Assign the source
document.documentElement.appendChild(elem); //Inject it into the DOM
}
injectScript("("+(function(window) {
// functions here
console.log("successfully injected content script"); // works
function foo(url){
$("#downloadPdfButton").click(handleDownloadFile(url));
}
foo("http://url.com/doc.pdf"); // breaks here
}).toString()+")(window)");
调用foo("http://url.com/doc.pdf")
,会中断说handleDownloadFile未定义。 如您所见,我什至尝试传递window
,然后将window.handleDownloadFile(url)
设置为click事件处理程序,但没有成功。
我希望即使有可能,也可以给我一些指导。
在声明handleDownloadFile时,您可以尝试以下操作-
window.handleDownloadFile = function(urlVal){
console.log("handleDownloadFile called");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.