简体   繁体   中英

Why does this bookmarklet JS code not work when put in an onclick handler?

I have a pretty typical bookmarklet code that's working perfectly for me in all browsers. However, when I take this code and put it in an HTML's element onClick handler, it doesn't work in IE (6, 7, or 8).

This is the code:

javascript: (
    function(){
        function l(i,u){
            var d=document;
            var s;
            try{
                s=d.standardCreateElement('script');
            }catch(e){}
            if(typeof(s)!='object')
                s=d.createElement('script');
            try{
                s.type='text/javascript';
                s.src='http://{Domain}/bk/' + u;
                s.id='s_' + i;
                d.getElementsByTagName('head')[0].appendChild(s);
            }catch(e){
            }
        }
        AppD = '{Domain}';          
        l('b', 'bk.js');
    }   
    )();

Compressed down as a bookmarklet, that looks like:

javascript:function(){function l(i,u){var d=document;var s;try{s=d.standardCreateElement('script');}catch(e){} if(typeof(s)!='object')  s=d.createElement('script'); try{s.type='text/javascript';s.src='http://{Domain}/bk/' + u;s.id='s_' + i;d.getElementsByTagName('head')[0].appendChild(s);}catch(e){}}AppD = '{Domain}';l('b', 'bk.js');})();

And that works perfectly. I've taken out the javascript: prefix, and put it into an element's onClick:

<img onclick="function(){function l(i,u){var d=document;var s;try{s=d.standardCreateElement('script');}catch(e){} if(typeof(s)!='object')   s=d.createElement('script'); try{s.type='text/javascript';s.src='http://{Domain}/bk/' + u;s.id='s_' + i;d.getElementsByTagName('head')[0].appendChild(s);}catch(e){}}AppD = '{Domain}';l('b', 'bk.js');})();" />

And that works well too, except than in IE, the code inside bk.js (the script that gets injected) complains that variable AppD is not defined...

Any ideas why this is happening?
Is there any limitation to the code one can put in an onClick handler?

Thanks! Daniel

Solved by adding window.AppD in front of the variable declaration.

Solution provided by Andrew Noyes in another question:

Are there any limitations to what can be done in an inline onclick handler?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM