Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

unable to run an external javascript using a bookmarklet

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...