unable to run an external javascript using a bookmarklet

南楼画角 提交于 2019-11-30 07:03:59

问题


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 html source code of the web page inserting the following < script > lines:

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

it works fine. But if I create a javascript: bookmarklet with the same lines, I obtain a blank page with the following string:

[object HTMLScriptElement]

whereas, if I create a bookmarklet adding the line

void(null);

to previous ones, the web page does not disapper but the script is not executed.

Why?


回答1:


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.



来源:https://stackoverflow.com/questions/2222417/unable-to-run-an-external-javascript-using-a-bookmarklet

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