Google Chrome behaves differently when the popup is being inspected

拥有回忆 提交于 2020-01-07 02:23:06

问题


In my attempts to learn how to write Google Chrome extensions I decided to write one where upon clicking a button in the popup the extension opens a new window and opens a new tab for every image on the page. Each tab's url is the src for each image. (I don't think this is particularly useful, I'm doing it merely as an exercise).

The weird thing is that it works exactly as I would expect when I have right-clicked on the extension icon and clicked 'inspect popup'. It doesn't work as expected when I just use it normally. When used normally it only opens 3 or 4 of the images (even weirder is that it's a different number of images it manages to open each time).

Here is my code

popup.html

<script type="text/javascript">

function getImages() {
    chrome.tabs.getSelected(null, function(tab){
        chrome.tabs.sendRequest(tab.id, {code: "getImages"}, function(images) {
            console.log(images);
            openImages(images);
        });
    });
}

function openImages(images) {
    chrome.windows.create({url: images[0]}, function(window) {
        for(var i=1; i<images.length; i++) {
            chrome.tabs.create({windowId: window.id, url: images[i]});
        }
    });
}

</script>

<button onclick="getImages();">Open images</button>

contentscript.js

chrome.extension.onRequest.addListener(
    function(request, sender, response) {
        if(request.code == 'getImages') {
            console.log("We're in!");
            var urls = [];
            var images = document.getElementsByTagName("img");

            for(var i=0; i<images.length; i++) {
                urls.push(images[i].src);
            }
            console.log(urls);
            response(urls);
        }
    }
);

Anyone have any ideas why this might be?


回答1:


When you open the new window, it gets focus, thereby the popup loses focus. Normally, Chrome closes an extension popup when it loses focus, but keeps it open when you're inspecting it with WebInspector. It seems that with the popup page, your images list variable gets killed.

3 ideas out of many more to fix this:

  • Instead of one URL, give an array of URLs to the windows.create() function. (best solution)
  • Create the window without giving it focus (add "focused ": false to the object given to the create function) and only give it focus when creating the last tab.
  • Open the tabs from the content script or a background page.


来源:https://stackoverflow.com/questions/7133185/google-chrome-behaves-differently-when-the-popup-is-being-inspected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!