When a download event is triggerd, a download bar will appear at the bottom of Chrome browser, which will trigger a window.resize event. Similarly, if we close the download bar, it also triggers a window.resize event. Can we distinguish whether the event is trigger by the download bar or manual operation? Thank you!!
You can't 100% know what caused the resize, but you can infer it based on the dimension changed. Here is a crude example of how you might go about that:
const state = {
width: window.innerWidth,
height: window.innerHeight
};
const DOWNLOAD_BAR_SIZE = 50;
const TOLERANCE = 0.25;
window.addEventListener("resize", () => {
let type = "resize";
const diffHeight = state.height - window.innerHeight;
const bounds = {
min: DOWNLOAD_BAR_SIZE * (1 - TOLERANCE),
max: DOWNLOAD_BAR_SIZE * (1 + TOLERANCE)
};
if (diffHeight >= bounds.min && diffHeight <= bounds.max) {
type = "download";
}
state.width = window.innerWidth;
state.height = window.innerHeight;
console.log(type);
});
This will keep track of the current size of the window, and future resizes on that window. When a download bar pops up from the bottom, the height dimension will change by ~50px. You can change the TOLERANCE
and DOWNLOAD_BAR_SIZE
constants to fit your needs.
A similar strategy can be applied to dev tools.
I think that there were some errors with the code, but the base was super useful.
bounds.min and bounds.max are calculated as boolean through comparison with dffHeight, but then again compared to diffHeight.
I preferred to make them numeric so that I can display their values.
const state = {
width: window.innerWidth,
height: window.innerHeight
};
const DOWNLOAD_BAR_SIZE = 50;
const TOLERANCE = 0.25;
let type = "resize";
window.addEventListener("resize", () => {
const diffHeight = state.height - window.innerHeight;
const bounds = {
min: DOWNLOAD_BAR_SIZE * (1 - TOLERANCE),
max: DOWNLOAD_BAR_SIZE * (1 + TOLERANCE)
};
console.log( "bounds.min = " + bounds.min + ", bounds.max = " + bounds.max + ", diffHeight = " + diffHeight );
if ( /* diffHeight >= bounds.min && */ diffHeight <= bounds.max) {
type = "download";
} else {
type = "resize";
}
state.width = window.innerWidth;
state.height = window.innerHeight;
console.log(type);
});
I moved the resize type indicator out of the listener in case I need to know elsewhere. Also, I am getting multiple events on closing the Toolbar, so I no longer check the minimum (for example, open toolbar fires an event with resize of 57, close fires three events of 14, 20, 23).
© 2022 - 2024 — McMap. All rights reserved.