[英]Chrome Extension: Center Created Window on Icon Click
首先:点击工具栏中的扩展图标,打开一个新创建的Window。
第二:在屏幕上设置创建的Window的Position。
第三:创建的Window加载“WebContent/index.html”
清单版本: v3
我在将以下代码从版本 2 迁移到清单版本 3 时遇到问题,并且我无法使用 window.screen.width 使屏幕宽度/高度使 window 居中,还有其他方法吗?
//Manifest Version 2
let ftdWindow = null;
chrome.action.onClicked.addListener(wind => {
console.log(`browserAction.onClicked`);
if (ftdWindow) {
console.log("The window exists!");
let info = {
focused: true
};
chrome.windows.update(ftdWindow.id, info, (w) => {
if (!w) {
console.log(`Error: The window does not exist!`);
ftdWindow = null;
}
});
} else {
chrome.storage.sync.get(['windowSize'], function(result) {
console.log(`storage.sync`);
let width = 1000;
let height = 700;
if (result.windowSize) {
width = parseInt(result.windowSize.width);
height = parseInt(result.windowSize.height);
}
let left = parseInt((window.screen.width - width) / 2);
let top = parseInt((window.screen.height - height) / 2);
chrome.windows.create({
url: chrome.runtime.getURL("WebContent/index.html"),
type: "panel",
left, top, width, height
}, function(window) {
ftdWindow = window;
});
});
}
});
//manifest.json
"permissions": [
"storage",
"unlimitedStorage",
"system.display"
]
//Manifest Version 3 - background.js
let ftdWindow = null;
chrome.action.onClicked.addListener(wind => {
console.log('Action.onClicked',ftdWindow);
if (ftdWindow) {
console.log("The window exists!");
let info = {
focused: true
};
chrome.windows.update(ftdWindow.id, info, (w) => {
if (!w) {
console.log(`Error: The window does not exist!`);
ftdWindow = null;
}
});
}else{
console.log("The window does not exist!");
chrome.storage.local.get("windowSize", (result) => {
let width = 1000;
let height = 700;
if (result.windowSize) {
width = result.windowSize.width;
height = result.windowSize.height;
}
new Promise((resolve, reject) => {
chrome.system.display.getInfo((displayInfo)=>{
resolve(displayInfo);
});
}).then((result)=>{
result.forEach((display) => {
if(display.isPrimary){
let left = parseInt((display.bounds.width - width) / 2);
let top = parseInt((display.bounds.height - height) / 2);
chrome.windows.create({
url: chrome.runtime.getURL("WebContent/index.html"),
type: "panel",
left, top, width, height
}, function(window) {
ftdWindow = window;
});
}
});
});
})
}
});
这将允许您在调整大小时保存 window 的高度/宽度,以便在上述代码中使用。
window.onresize = function() {
chrome.storage.local.set({
windowSize: {
height: Math.max(window.outerHeight, 300),
width: Math.max(window.outerWidth, 400)
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.