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

岁酱吖の 提交于 2019-12-11 16:06:27

问题


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


回答1:


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?



来源:https://stackoverflow.com/questions/861102/why-does-this-bookmarklet-js-code-not-work-when-put-in-an-onclick-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!