Requiring
First: Click on the Extension Icon in the toolbar to open a newly Created Window.
Second: Set Position of the Created Window on the Screen.
Third: The Created Window Loads "WebContent/index.html"
Current Extension Settings
Manifest Version: v3
Issue
I'm having issues migrating the below code to manifest version 3 from version 2, and I'm not able to get the screen width/height to center the window by using window.screen.width, is there another way?
Code Using
//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;
});
});
}
});
CodePudding user response:
Solution
//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;
});
}
});
});
})
}
});
Additional Code - main.js
This will allow you to save the height/width of the window on resize for use in the above code.
window.onresize = function() {
chrome.storage.local.set({
windowSize: {
height: Math.max(window.outerHeight, 300),
width: Math.max(window.outerWidth, 400)
}
});
}