unable to run an external javascript using a bookmarklet

后端 未结 1 828
情歌与酒
情歌与酒 2020-12-15 14:01

Totally newbie about JS.

I need to use an external script which modifies some elements in the current page accessing it as a bookmarklet.

If I modify the htm

1条回答
  •  悲&欢浪女
    2020-12-15 14:42

    A common practice is to simply use a self-executing function expression, something like this:

    (function () {
      var s=document.createElement('script');
      s.type='text/javascript';
      s.src='script.js';
      document.getElementsByTagName('head')[0].appendChild(s);
    }());
    

    Bookmarklet:

    javascript:(function(){var s=document.createElement('script');s.type='text/javascript';s.src='script.js';document.getElementsByTagName('head')[0].appendChild(s);}());
    

    The function will return undefined (no return value supplied) preventing the navigation.

    Note also that this will avoid creating global variables (like s) that can overlap with other variables used on the page, because all variables are created in the scope of the anonymous function.

    0 讨论(0)
提交回复
热议问题