Reputation: 3287
I have a chrome extension that creates popups in a static location. However, if the user moves the popup and then closes it. I'd like to set the next popup to open in the same location the previous one was closed.
My background page is already listening for onRemoved and onFocusedChanged, but those only return the Window ID.
Is there a way to get the last top
and left
locations of a popup window after a user moves it, and on or before it is closed?
Upvotes: 1
Views: 1108
Reputation: 73616
We can use beforeunload
event and we need a synchronous method of saving data in order to guarantee it successfully completes before the execution context of the page is destroyed.
If the popup runs your extension page.
Popup's page script can save the size in the synchronous localStorage shared between all your extension pages, including the background script where you can use the saved value next time to create the popup window.
window.addEventListener('beforeunload', () => {
localStorage.windowSize = JSON.stringify({
left: window.screenX,
top: window.screenY,
width: window.outerWidth,
height: window.outerHeight,
});
});
If the popup runs a web URL.
We'll have to use a content script where we can abuse chrome.runtime.connect to pass the data synchronously in the port name to the background script which will parse and save the data in chrome.storage.local. Of course you can use this approach for the first case as well.
content script:
window.addEventListener('beforeunload', () => {
chrome.runtime.connect({
name: 'windowSize:' + JSON.stringify({
left: window.screenX,
top: window.screenY,
width: window.outerWidth,
height: window.outerHeight,
})
});
});
Make sure the content script runs inside the popup, for example, via chrome.tabs.executeScript in your background script right after creating the popup window.
background script:
chrome.runtime.onConnect.addListener(port => {
if (port.name.startsWith('windowSize:')) {
const windowSize = JSON.parse(port.name.slice('windowSize:'.length));
chrome.storage.local.set({windowSize});
}
});
Upvotes: 1