Search code examples
javascriptgoogle-chrome-extensionchrome-custom-tabs

Sending mouse move through chrome tabs


I have this code:

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
        var host = tab.url;
        var reg = new RegExp("test", "gi");
        if(reg.test(host)) {
            chrome.tabs.executeScript(
                tabId,{
                    code:"$(window).on('mousemove', function(e) {var posX = e.pageX;var posY = e.pageY;console.log(posX);console.log(posY);});"
                },
                function(results) {
            });
        }
    }
});

If I enter the page the mouse move is capture. In console mouse coordinates are showing. Now, I would like to send the same mouse coordinates to the other chrome tab. In the other tab mouse coordinates should be captured and this code above should show posX and poxY in console. I am asking for some tips on what functions, methods or keywords to pay attention to doing this.


Solution

  • Without a server, you can do this with Window.postMessage(). postMessages allows communication between two window objects.

    So in your parent window, you'd have something along the lines of this:

    //Window-A.html
    document.onmousemove = function (e) {mousePos(e);};
    
    var mouseX = 0;
    var mouseY = 0;
    
    function mousePos (e) {
        if (!mie) {
            mouseX = e.pageX; 
            mouseY = e.pageY;
        }
        else {
            mouseX = event.clientX + document.body.scrollLeft;
            mouseY = event.clientY + document.body.scrollTop;
        }
    
        document.show.mouseXField.value = mouseX;
        document.show.mouseYField.value = mouseY;
    
        return true;
    }
    
    var newWindow = window.open(...);
    newWindow.postMessage(`x: ${mouseX}, y: ${mouseY}`, '*');
    

    And then in the receiving window, you add the listener:

    //Window-b.html
    window.addEventListener("message", function (event) {
        console.log(event.data); // will log out the values from the postMessage from Window-A.html
    }, false);