punkrockbuddyholly
punkrockbuddyholly

Reputation: 9794

Google Chrome behaves differently when the popup is being inspected

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?

Upvotes: 0

Views: 796

Answers (1)

Arnulf
Arnulf

Reputation: 58

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.

Upvotes: 1

Related Questions