1
chrome.browserAction.onClicked.addListener(function (tab) {
    var currentWidth = 0;
    var currentHeight = 0;

    chrome.windows.getCurrent(function(w) {
    // You can modify some width/height here
       alert(w.top);
       currentWidth = w.left / 2;
       currentHeight = w.top / 2;
    });

    var w = 440;
    var h = 220;
    var left = (screen.width  / 2) - (w / 2) - currentWidth;
    var top = (screen.height / 2) - (h / 2) - currentHeight;

    chrome.windows.create({
        'type': 'popup',
        'width': w,
        'height': h,
        'left': left,
        'top': top}, function (window) {
        chrome.tabs.executeScript(newWindow.tabs[0].id, {
            code: 'document.write("hello world");'
        });
    });
});

The window shows up in the middle but when the current window is resized to a smaller view, the window shows up at where the center of the screen would be not at the center of current window.

When I remove the /2 from currentHeight or currentWidth, the window shows, but it's at the wrong location (too far off to one side).

Xan
  • 74,770
  • 16
  • 179
  • 206
user299709
  • 4,922
  • 10
  • 56
  • 88

1 Answers1

2

You're misusing the asynchronous API.

See this answer for a general description of the problem.

In your case, it should sufficient to move the logic into your first callback:

chrome.browserAction.onClicked.addListener(function (tab) {    
    chrome.windows.getCurrent(function(win) {
        var currentWidth = 0;
        var currentHeight = 0;
        var width = 440;
        var height = 220;
    // You can modify some width/height here
       alert(win.top);
       currentWidth = win.left / 2;
       currentHeight = win.top / 2;

        var left = (screen.width  / 2) - (width / 2) - currentWidth;
        var top = (screen.height / 2) - (height / 2) - currentHeight;

        chrome.windows.create(
            {
                'type': 'popup',
                'width': width,
                'height': height,
                'left': left,
                'top': top
            }, function (window) {
                chrome.tabs.executeScript(window.tabs[0].id, {
                    code: 'document.write("hello world");'
                });
            }
        );
    });
    // Here, currentWidth/currentHeight is not assigned yet
});
Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206