Chrome扩展:如何使当前窗口的对话框中心

chrome extension: how to make dialog center of current window?

本文关键字:对话框 窗口 扩展 何使当 Chrome      更新时间:2023-09-26
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");'
        });
    });
});

窗口显示在中间,但是当当前窗口的大小被调整到一个较小的视图时,窗口显示在屏幕中心不是当前窗口中心的地方。

当我从currentHeight或currentWidth中删除/2时,窗口显示,但它位于错误的位置(离一侧太远)。

你在滥用异步API。

请参阅这个问题的一般描述。

在您的例子中,将逻辑移动到第一个回调中应该足够了:

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
});