views:

281

answers:

2

I'm working on a bookmarklet that gives the full path to an image when you click on any image on a web page. The image is then downloaded on our servers, and we do business stuff to it.

Currently, the script parses out the src attribute using jQuery, then has some dumb logic that usually works, but quite often it does not.

Now, I could keep writing ugly code to do a better job of parsing out the url using regex and stuff, but I feel like there should be some better way of doing this.. Finding some way to mimic (as in firefox) "Right-Click => Copy Image Location" would be fantastic.

Here is the relevant js code I have currently (buggy, but it usually works).. Any innovative ideas on how to better accomplish this?

var imgsrc;
$("img").click(function() {
  imgsrc = $(this).attr("src");
  var url = document.URL;

  if (window.location.pathname != "/") {
    var pathLoc = url.indexOf(window.location.pathname);
    url = url.substr(0, pathLoc + 1);
  } else if (window.location.pathname.substr(0,1) == "/") {
    url = url.substr(0, url.length - 1);
  }

  if (imgsrc.toLowerCase().indexOf("http://") != 0) {
    imgsrc = url + imgsrc;
  }

  window.open("http://www.mycompany.com/whatever?imgsrc=" + imgsrc + "");
});

$("img").hover(function () {
  $(this).css({'border' : '4px solid #ff0000'});
  }, function () {$(this).css({'border' : ''});
});
A: 

To add a menu to the contextual menu, you have to create an extension for firefox. I've created an extension for wikipedia here: you might be interested by the code.

Pierre
+1  A: 

I believe most browsers normalize the SRC property (I mean the DOM property, not getAttribute('src')). So you could try:

$("img").click(function() {
    window.open("http://www.mycompany.com/whatever?imgsrc=" + this.src + "");
});

If that doesn't work then I know for a fact that anchor tags have their HREF properties normalized; this will definitely work:

$("img").click(function() {
    var fullSrc = $('<a/>').attr('href', this.src)[0].href;
    window.open("http://www.mycompany.com/whatever?imgsrc=" + fullSrc + "");
});
J-P
the first one totally worked and totally killed 10 lines of bad code. Thanks!
Stephen J. Fuhry
actually, it's pretty important to escape your url.. now it works for everything:$("img").click(function() { window.open("http://www.mycompany.com/whatever?imgsrc=" + escape(this.src) + "");});
Stephen J. Fuhry
@fuhrysteve, yup, but you should be using encodeURIComponent()
J-P