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
时,窗口会显示,但它位于错误的位置(距离一侧太远)。
答案 0 :(得分:2)
您滥用异步API。
有关问题的一般说明,请参阅this answer。
在您的情况下,将逻辑移动到您的第一个回调中应该足够了:
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
});