开发者

How can I test JavaScript without placing it on the website?

I'm talking about something like GreaseMonkey but that would accept the script just as it would be on the website. Adding external scripts to Greasemonkey has been a pain for me so far.

So, I have a client who wanted me to write a specific script for him. Because the script reads the URL of the page visited by a user I can only test it on the website but i don't have access to the source code of the website. I'd like to make sure I deliver to the client a 100% working script so I would love to test it first.

How can I do that? Any plugins that would just allow me to copy the script and would run it ev开发者_运维百科ery time I load a page of the website?


Obviously, if you can, you want to set up a copy of the page on which the script operates, on a local web server where you can play around with things.

If that isn't possible for whatever reason, you can inject your script directly into their site when you're looking at it with your browser using a bookmarklet. The code to do it is roughly:

var script = document.createElement('script');
script.src = "...the path to your script file, ideally on a local web server rather than a file:// path...";
document.body.appendChild(script);

Once you've tweaked the above (pretty much just supplying the src value), you can turn it into a bookmark via the Crunchinator. Once you have your bookmarket, just visit the site you're developing this for and click your bookmarklet, and your script will be added to the page (just for you, obviously, and just for that visit to the page).

Then your develop/test cycle becomes:

  • Modify the script file (for instance, to fix a bug)
  • Open their site
  • Click your bookmarklet to add your script file to the page


Using something like GreaseMonkey can lead to unexpected results since GM runs outside of the Browsers Sandbox and GM scripts always run after everything else has loaded.

My solution for this would probably be:

  1. Setup a local WebServer
  2. Use "Save page..." to get the page contents, then put them on your localhost
  3. Now add your script to the page etc. and make it work

That gives you A) A flexible development environment and B) more "realworld" results, hell you can even edit you hosts file to use the same URL that your client's page has (of course you need to re-edit the file if you want to visit the original page) and C) you can test in IE etc. too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜