0

I know hat it is possible, but I am not quite sure how to do it the 'right' way, as to ensure there are no conflicts.

I came across this question: Cannot call functions to content scripts by clicking on image . But it is so convoluted with random comments that it's hard to understand what the corrected way was.

Use case:

Html pages have a div on the page where they expect anyone using the Chrome extension to inject a picture. When users click on he picture, I want to somehow notify an event script. So I know I need to register a listener so the code inserted messages the event script.

Can I get some indication on what code to inject through the content script? I saw that sometimes injecting jquery directly is advised.

I am trying to avoid having the html page to post a message to itself so it can be intercepted. Thanks

0

1 Answer 1

2

With the help of Jquery something like this would capture the image onclick event and allow you to pass a message to a background page in the Chrome Extension:

$("img").click(function(){ var imageSrc = $(this).attr("src"); //Post to a background page in the Chrome Extension chrome.extension.sendMessage({ cmd: "postImage", data: { imgSrc: imageSrc } }, function (response) { return response; }); }); 

Then in your background.js create a listener for the message:

chrome.extension.onMessage.addListener( function (request, sender, sendResponse) { if (request.cmd == "postImage") { var imageSrc = request.data.imgSrc; } }); 
Sign up to request clarification or add additional context in comments.

8 Comments

Hello, I don't know much about jquery, but would this not insert the image in the div once the click on an image is registered? or Am I reading this wrong? thanks
Yes that's right, is there something you want to do in between this?
Yeah, that is not what I need. Sorry. There is only a div in the original html, where an image should be inserted when chrome loads the page. This image should also be able to report back clicks hat happen on it. So basically I want to add a clickable image where a the div with an specific id.
You mention "There is only a div in the original html, where an image should be inserted when chrome loads the page" Where does this image originate from? Will it always be the same image or dynamically populated somewhere else?
The images will be downloaded from a server, each time a page with a a div that requires an image (specific id or something) one image will be pulled from the repository. I need to obviously monitor the number of images and download more as they are used up. I think I know how to do the whole part of acquiring the images, I just don't know how to capture clicks on the injected images, as these need to be reported back to the server. To keep track of what images get people to click.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.