How to add an external javascript file and run a function through a bookmarklet?

Hey. I am trying to create a javascript bookmarklet that will add a link to an external javascript source on a page that is outside the domain. However, nothing happens when I run the bookmarklet without errors, and the code on the page never changes. Any ideas? Here is the bookmarklet I'm trying to use. Thank you for your time.

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

You can also achieve this with a callback:

    var addScript=function(filename,callback){
            var e=document.createElement('script');
            e.type = 'text/javascript';
            e.src = filename;
            if(callback){
                e.onloadDone=false;//for Opera
                e.onload=function(){e.onloadDone=true;callback();};
                e.onReadystatechange=function(){
                    if(e.readyState==='loaded'&& !e.onloadDone){
                        e.onloadDone=true;callback();
                    }
                }
            }
        if(typeof(e)!=='undefined'){
            document.getElementsByTagName('head')[0].appendChild(e);
        }
    }
addScript('http://yoursite.com/js/yourScript.js',function(){functionFromYourScript();});

(of course, you will want to optimize this to insert it into the bookmarklet, but you will get the idea ...)

+2
source

. , jQuery, .

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

, JS , , :

<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>
0

You need to add code that

  • inserts the necessary script tags and then
  • use timer interval to re-check an object from an imported script

Here is a 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();
0
source

Source: https://habr.com/ru/post/1768892/


All Articles