I'm trying to write a bookmarklet which adds a JSONP call into a page like this:
我正在尝试编写一个书签,将JSONP调用添加到这样的页面中:
javascript:(function(){
var myFunction = (window.function(data){alert('my function is firing with arg' + data)});
var j = 'http://localhost/jsonscript.js';
var s = document.createElement('script');
s.src = j;
document.getElementsByTagName('head')[0].appendChild(s);
})();
where the script src appended into the page contains
附加到页面中的脚本src包含的位置
myFunction('foo');
But there's an error when I click the bookmarklet -- myFunction is not defined. How do I "export" that function outside the scope of my bookmarklet so that when called from the appended script tag it works?
但是当我点击书签时出现错误 - 未定义myFunction。如何在我的bookmarklet范围之外“导出”该函数,以便从附加的脚本标记调用时它可以工作?
Edit: I figured out that I can just pack the script element's innerHTML with raw JavaScript. This works but it's ugly. I would still like to figure out a better way.
编辑:我发现我可以用原始JavaScript打包脚本元素的innerHTML。这有效,但很难看。我还是想找出一个更好的方法。
1 个解决方案
#1
4
Define the function on the window object:
在窗口对象上定义函数:
window.myFunction = ...
With JSONP requests, you'll usually want some type of counter to increment, ie:
对于JSONP请求,您通常需要某种类型的计数器来递增,即:
var counter = 1;
var myFuncName = "myFunction" + counter;
var j = 'http://localhost/jsonscript.js?callback=' + myFuncName;
window[myFuncName] = function (data) {...};
// remove function after timeout expires
setTimeout(function () { delete window[myFuncName] }, 5000);
#1
4
Define the function on the window object:
在窗口对象上定义函数:
window.myFunction = ...
With JSONP requests, you'll usually want some type of counter to increment, ie:
对于JSONP请求,您通常需要某种类型的计数器来递增,即:
var counter = 1;
var myFuncName = "myFunction" + counter;
var j = 'http://localhost/jsonscript.js?callback=' + myFuncName;
window[myFuncName] = function (data) {...};
// remove function after timeout expires
setTimeout(function () { delete window[myFuncName] }, 5000);