Calling a function created inside a bookmarklet
bookmarklet, javascript, scope
Solution
Define the function on the window object:
window.myFunction = ...
With JSONP requests, you'll usually want some type of counter to increment, ie:
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);
Problem
I'm trying to write a bookmarklet which adds a JSONP call into a page like this: ``` 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 ``` 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? 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.