Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function created inside a bookmarklet

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.

like image 334
AmbroseChapel Avatar asked Oct 04 '22 13:10

AmbroseChapel


1 Answers

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);
like image 190
Abdullah Jibaly Avatar answered Oct 10 '22 03:10

Abdullah Jibaly