chrome扩展:如何使对话框位于当前窗口的中心? [英] chrome extension: how to make dialog center of current window?

查看:69
本文介绍了chrome扩展:如何使对话框位于当前窗口的中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

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

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).

推荐答案

您正在滥用异步API.

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

这篇关于chrome扩展:如何使对话框位于当前窗口的中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆