gpt4 book ai didi

javascript - Chrome 扩展 : how to make dialog center of current window?

转载 作者:行者123 更新时间:2023-11-30 17:22:35 25 4
gpt4 key购买 nike

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

窗口显示在中间,但是当当前窗口调整为较小的 View 时,窗口显示在屏幕中心不在当前窗口中心的位置。

当我从 currentHeight 或 currentWidth 中删除 /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
});

关于javascript - Chrome 扩展 : how to make dialog center of current window?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24862664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com