使书签执行下载的功能 [英] Make A Bookmarklet Execute A Function That It Downloads
问题描述
我想创建一个书签,该书签下载一个远程javascript文件,该文件中定义了一个函数,然后使用硬编码到该书签中的参数执行该函数.
I would like to create a bookmarklet that downloads a remote javascript file in which a function is defined and then executes that function with parameters that are hard-coded into the bookmarklet.
这是您的标准下载并运行远程脚本"书签,在最后一行中有一个额外的函数调用:
Here is your standard "download-and-run-remote-script" bookmarklet with an extra function call in the last line:
javascript:( function () {
var new_script = document.createElement("script");
new_script.src = "http://mydomain.com/myscript.js";
document.body.appendChild(new_script);
do_stuff('Hello World!');
} ) ();
这是myscript.js的内容:
Here are the contents of myscript.js:
function do_stuff(input_variable) {
alert(input_variable);
}
按照书面规定,这不会做任何事情.为什么不?我应该怎么做?
As written, this doesn't do anything. Why not? What should I do differently?
推荐答案
脚本异步加载.这意味着在您尝试运行该函数之前,脚本不会完成加载.
Scripts load asynchronously. That means that the script doesn't finish loading before you try to run the function.
解决方案1.)小书签中的myvar = 'Hello World!'
和myscript.js中的do_stuff(myvar)
.
Solution 1.) myvar = 'Hello World!'
in bookmarklet and do_stuff(myvar)
in myscript.js.
解决方案2.)将onload事件用于创建的脚本元素.更强大,但更复杂.
Solution 2.) Use the onload event for the script element you create. More robust, but more complicated.
这篇关于使书签执行下载的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!