4

Making safari extension imageSearch By google.

Here is my source.

injected.js

document.addEventListener("contextmenu", handleContextMenu, false);

function handleContextMenu(event) {
    safari.self.tab.setContextMenuEventUserInfo(event, event.target.nodeName);
}

global.html

<!DOCTYPE HTML>
<script type="text/javascript" src="jquery.js"></script>
<script>
safari.application.addEventListener("contextmenu", handleContextMenu, false);
function handleContextMenu(event) {
    var query = event.userInfo;
    if (query === "IMG") {
        event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
    }
}

safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
    if (event.command === "imageSearch") {  


       /*How I get image Url??? */
       var imageUrl="";


    /*
        var url = "http://images.google.com/searchbyimage?image_url="+imageUrl;
        var tab = safari.application.activeBrowserWindow.openTab("foreground");
        tab.url = url;

    */

    }
}

My goal is..

  1. if mouse rightclick add "Search by Google With This Image" int the context menu. (clear)

  2. and click "Search by Google With This Image" google it. (???)

so i want to know image url.

What should I do?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
dm6637
  • 43
  • 4

2 Answers2

4

You could try this:

  1. store the whole node into the event's userInfo:

    function handleContextMenu(event) {
        safari.self.tab.setContextMenuEventUserInfo(event, event.target);
    }
    
  2. add some global javascript variable to your global.html (e.g. var lastClickedImg),

  3. change your handleContextMenu function to store the event.userInfo in function handleContextMenu to this variable:

    function handleContextMenu(event) {
        var query = event.userInfo;
        if (query.nodeName === "IMG") {
            lastClickedImg = query;
            event.contextMenu.appendContextMenuItem("imageSearch", "Search Google with this image");
        }
    }
    
  4. in your function performCommand you will easily get the image's url from lastClickedImg:

    lastClickedImg.src
    
DaTa
  • 229
  • 1
  • 7
0

You can find image URL by placing an event listener for contextmenu in an injected script.

function contextMenuHandler(event)
{
    var url = event.target.src;
    safari.self.tab.setContextMenuEventUserInfo(event, url);
}

document.body.addEventListener("contextmenu", contextMenuHandler, false);

And then recovering the image src in command event

var imageUrl = event.userInfo;

You should also do some validation to make sure it's an image.

Abcd Efg
  • 2,146
  • 23
  • 41