简体   繁体   中英

Chrome Extension: Detect click outside of chrome extension

In short, I am trying to make the extension itself reload when anything is clicked in the browser portion of the screen. I found, Capturing all the <a> click event , which gave me

window.onclick = function(e) { alert(e.target);};

but this only throws an alert if something is clicked inside the extension. Is there a way to detect a click outside of the extension itself and make that reload the extension?

Off the top of my head, I will say you can only get clicks from individual tabs opened. So you'll miss the URL bar and any other portion of the browser that's outside the tab area.

Here's how you can capture clicks on all tabs. Note: Place code in your background page.

chrome.tabs.query({}, function(tabs){
    for(var i = 0; i < tabs.length; i++){
        chrome.tabs.executeScript( tabs[i].id, {code:"window.onclick = function(e) { alert(e.target);};"},
                function(){} );
    }
});
chrome.tabs.onCreated.addListener(function(tab)  { 
   chrome.tabs.executeScript( tab.id, {code:"window.onclick = function(e) { alert(e.target);};"},
   function(){} );
});
chrome.tabs.onUpdated.addListener(function(tab)  { 
   chrome.tabs.executeScript( tab.id, {code:"window.onclick = function(e) { alert(e.target);};"},
   function(){} );
});

To notify your extension that a click occured on one of your tabs, use chrome.runtime.sendMessage -- you can intercept this message in your background page by adding chrome.runtime.onMessage.addListener . When you received the message, you can reload the extension using chrome.runtime.reload();

So instead, of calling alert() when a click happens, use chrome.runtime.sendMessage , and when your background page gets the message, chrome.runtime.reload should do the job of reloading the extension.

Final code, all placed in your background page, would look like so:

chrome.tabs.query({}, function(tabs){
    for(var i = 0; i < tabs.length; i++){
        chrome.tabs.executeScript( tabs[i].id, {code:"window.onclick = function(e) { chrome.runtime.sendMessage({msgID: "click_event"});};"},
                function(){} );
    }
});
chrome.tabs.onCreated.addListener(function(tab)  { 
   chrome.tabs.executeScript( tab.id, {code:"window.onclick = function(e) { chrome.runtime.sendMessage({msgID: "click_event"});};"},
   function(){} );
});
chrome.tabs.onUpdated.addListener(function(tab)  { 
   chrome.tabs.executeScript( tab.id, {code:"window.onclick = function(e) { chrome.runtime.sendMessage({msgID: "click_event"});};"},
   function(){} );
});

chrome.runtime.onMessage.addListener(function(req, sender, resp){

    if(req.msgID.indexOf("click_event") > -1)
    {   
       chrome.runtime.reload();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM