Search code examples
popupgoogle-chrome-extensionmouseclick-event

Obtain mouse coordinates of the pop-up window not the background window


I have a bit of a problem here. Based on my previous question asked I have developed an extension that takes note of the mouse-clicks and marks the place.

However, when I click on a link to open a pop-up; the mouse-clicks that are marked are on the background window and not on the pop-up.

Is this a security issue or something ?

background.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    chrome.tabs.captureVisibleTab(null, {format:"png"}, function(dataUrl){

    var img = new Image();
    img.onload = function(){
        var canvas = document.getElementById("canvas");
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext("2d");

        ctx.drawImage(img, 0, 0);
        ctx.arc(request.x, request.y, 5, 0, Math.PI*2, true);
        ctx.fillStyle = "rgb(255,0,0)";
        ctx.fill();

        chrome.tabs.create({url: canvas.toDataURL("image/png")});
    };
    img.src = dataUrl;

});
sendResponse({});
});
<body>
    <canvas id="canvas"></canvas>
</body>

content_script.js :

window.addEventListener("click", function(event) {
    chrome.extension.sendRequest({x: event.x, y: event.y});
});

Solution

  • This happens because current window and focused window are two different things in Chrome API. Passing null to chrome.tabs.captureVisibleTab() takes current window, which for popups means a background window. As it says in the docs:

    The current window is the window that contains the code that is currently executing. It's important to realize that this can be different from the topmost or focused window.

    To make screenshot of a window that sent the request we need to specify it explicitly:

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
        chrome.tabs.captureVisibleTab(sender.tab.windowId, {format:"png"}, function(dataUrl){
            ...
        });
    });