views:

34

answers:

2

Hi I'm trying to make a javascript bookmarklet that will add a link to an external javascript source to a page that is off the domain. However nothing happens when I run the bookmarklet no errors and the code on the page never changes. Any ideas? Here is the bookmarklet I'm trying to use. Thanks for your time.

javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://mycode.com/autopopulator.js';autopopulate();})(); 
A: 

I've never attempted to create a bookmarklet. But I have found this example online which incorporates jQuery which could be of some use to you.

http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/

It explains on how to link to external JS files and incorporate other files within that, but I think the kind of thing you are looking for is:

<a href="javascript:(function(){var head=document.getElementsByTagName('head')[0],script=document.createElement('script');script.type='text/javascript';script.src='http://www.site.com/your-javascript.js?' + Math.floor(Math.random()*99999);head.appendChild(script);})(); void 0">Your Bookmarklet Name</a>
Malachi
That still doesn't show any changes. It is as if it isn't changing anything on the page at all.
NCX001
A: 

You need to add code that

  1. inserts the required script tags and then
  2. use a timer interval to repeatedly check for an object from the imported script

Here's sample code:

function writeTags(){
    //write the script tags
}
function check(){
    // example for prototype library
    if(window.Prototype && Prototype.Version){
        doActualWork();
    }else{
        window.setTimeout(check, 200);
    }
}
function doActualWork(){
    // this your actual code that requires
    // the loaded library
}
writeTags();
check();
seanizer
I'm curious as to what I accomplish by checking for an object from the script?
NCX001
if you find the object, you know the script is loaded and you can use it's methods. it's a common check in JavaScript when working with libraries
seanizer