1

I am building a bookmarlet based on this site: http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/

This is the code of bookmarlet:

javascript:(function(){
    var head=document.getElementsByTagName('head')0],
         script=document.createElement('script');
    script.type='text/javascript';
    script.src='http://myserver.com/bookmarlet-remote.js?' + Math.floor(Math.random()*99999);
    head.appendChild(script);
})(); 
void 0

How I can pass a variable from the bookmarlet (above code), to bookmarlet-remote.js ?

I've tried after var myNewvar='myValue', without success, Any Idea?

1
  • 1
    Try creating a variable without using var. Commented May 24, 2011 at 16:11

3 Answers 3

5

All JS code on a page (including bookmarklet code and scripts included have) have access to the global scope. If you define a variable without the var prefix it will be available to all other scripts.

It might be a good idea to be explicit about this. do window.myVar = "foo"; to clearly signal that you are working with global variables.

Sign up to request clarification or add additional context in comments.

Comments

1

Using var in the function makes it local to that function. To make it global you have to add it to the scope of the window, so:

window.newVariable = window.newVariable || 'Your new value here';

OR

window['newVariable'] = 'Your new value here';

3 Comments

The first option prevents you from overwriting the variable if you've already defined it, the second just adds it to the set of variables available in the global scope.
You want || not |. || is OR, | is bitwise OR, which is completely different
Also, it needs to be window not Window.
0

You'd create a public variable.

window.rnd = Math.floor(Math.random()*99999);

In bookmarlet-remote.js you just access the variable.

2 Comments

drop the var here since the code he writes is inside a function body.
yup... saw my mistake and corrected it before I saw your comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.