skip to Main Content

I save the position of a window when it’s closed:

const savePositionToStorage = (position) => {
    localStorage.setItem('windowPosition', position);
    console.log('Position saved:', position);
}

const getPositionFromStorage = () => {
    const position = localStorage.getItem('windowPosition');
    return position ? position :  "top=0,left=0,width=800,height=1000";
}

and open a window like this:

const handleExpandClick = (id) => {
    const windowFeatures = getPositionFromStorage();

    const pdfWindow = window.open(
        `http://127.0.0.1:8000/transactions/matching_evidence/${id}#toolbar=0,view=FitH`,
        "pdf",
        windowFeatures,
    );

    pdfWindow.onload = () => {
        pdfWindow.onbeforeunload = () => {
            savePositionToStorage(`top=${pdfWindow.screenY},left=${pdfWindow.screenX},height=${pdfWindow.innerHeight},width=${pdfWindow.innerWidth}`)
        }
    }

}

The user should be able to save the current location and size of the window, so the user doesn’t have to readjust the pop-up every time.
It works with the current browser monitor, but if I close it on another monitor, it will simply pop up on the furthest right of the current browser monitor.

Is there a way to archive what I want?

Chrome would be the browser the users are using.

2

Answers


  1. Chosen as BEST ANSWER

    For some reason, it works now. I deleted the local storage, and when I tried again, it just worked. I didn't really change anything, except that I'm saving the data as a stringnifyed json:

    const savePositionToStorage = (position) => {
        localStorage.setItem('windowPosition', JSON.stringify(position));
        console.log('Position saved:', position);
    }
    
    const getPositionFromStorage = () => {
        const position = JSON.parse(localStorage.getItem('windowPosition'));
        return position ? position : { top: 0, left: 0, width: 800, height: 1000 };
    }
    
    
    // #region Click Events
    const handleExpandClick = async (id) => {
        const storedPosition = getPositionFromStorage();
        const windowFeatures = `top=${storedPosition.top},left=${storedPosition.left},height=${storedPosition.height},width=${storedPosition.width}`;
    
        const pdfWindow = window.open(
            `http://127.0.0.1:8000/transactions/matching_evidence/${id}#toolbar=0,view=FitH`,
            "pdf",
            windowFeatures,
        );
    
    
        pdfWindow.onload = () => {
            pdfWindow.onbeforeunload = () => {
                savePositionToStorage({ "top": pdfWindow.screenY, "left": pdfWindow.screenX, "height": pdfWindow.innerHeight, "width": pdfWindow.innerWidth })
            }
        }
    }
    // #endregion
    

    I will ask my colleagues to try the code later and I'll report back if it works there. Very strange

    Edit: Okay, the problem seems to be Window management. This has to be set to allow. I don't know how to get the permissions yet

    Edit: I found the problem now. I simply needed to wait for the promise and go from there (full code):
    Be aware that this won't work with FireFox https://developer.mozilla.org/en-US/docs/Web/API/Window/getScreenDetails

    // #windowLocation
    const savePositionToStorage = (position) => {
        localStorage.setItem('windowPosition', JSON.stringify(position));
    }
    
    const getPositionFromStorage = () => {
        const position = JSON.parse(localStorage.getItem('windowPosition'));
        return position ? position : { top: 0, left: 0, width: 800, height: 1000 };
    }
    
    const loadWindow = (windowFeatures, id) => {
        const pdfWindow = window.open(
            `http://127.0.0.1:8000/transactions/matching_evidence/${id}#toolbar=0,view=FitH`,
            "pdf",
            windowFeatures,
        );
    
        pdfWindow.onload = () => {
            pdfWindow.onbeforeunload = () => {
                savePositionToStorage({ "top": pdfWindow.screenY, "left": pdfWindow.screenX, "height": pdfWindow.innerHeight, "width": pdfWindow.innerWidth })
            }
        }
    }
    // #endregion
    
    
    // #region Click Events
    const handleExpandClick = (id) => {
        const storedPosition = getPositionFromStorage();
        const windowFeatures = `top=${storedPosition.top},left=${storedPosition.left},height=${storedPosition.height},width=${storedPosition.width}`;
    
        // if there are multiple screens, ask the user for window Management permissions.
        // supported browser: https://developer.mozilla.org/en-US/docs/Web/API/Window/getScreenDetails
        if (window.screen.isExtended) {
            window.getScreenDetails().then(() => {
                loadWindow(windowFeatures, id);
            });
        } else {
            loadWindow(windowFeatures, id);
        }
    }
    // #endregion
    

  2. I’ve wondered the same thing myself. Unfortunately, there’s no direct way to reliably determine the monitor a window was last closed on using JavaScript. Browsers do not provide an API to get the monitor information for a window.

    Here’s why it’s tricky:

    • Security Concerns: Accessing information about monitors could be used for malicious purposes, so browsers limit this access.
    • Cross-Platform Issues: Each operating system and browser handle multi-monitor setups differently. A solution that works on Chrome on Windows might not work on macOS or Linux.

    Workarounds

    Here are some alternative approaches to consider:

    1. Manual Adjustment:

    • You can guide the user to adjust the window position manually the first time they open it on a new monitor.
    • Provide UI elements in the popup window to allow the user to manually reposition and resize the window, and save these changes.

    2. (Partial) Solution using screen.availHeight/Width:

    • You can use screen.availHeight and screen.availWidth to get the available screen space, which can give you an idea of the monitor’s resolution.
    • However, this won’t tell you the exact monitor, and the user might need to adjust the window if the available screen space changes between monitors.

    Example (Partial Solution):

    const handleExpandClick = (id) => {
      const storedPosition = getPositionFromStorage();
      const availableWidth = screen.availWidth;
      const availableHeight = screen.availHeight;
    
      // If the stored position is outside the current monitor's bounds, 
      // reposition the window closer to the center.
      let updatedPosition = storedPosition;
      if (storedPosition.left > availableWidth || storedPosition.top > availableHeight) {
        updatedPosition = `top=${availableHeight / 2},left=${availableWidth / 2},width=800,height=600`;
      }
    
      const pdfWindow = window.open(
        `http://127.0.0.1:8000/transactions/matching_evidence/${id}#toolbar=0,view=FitH`,
        "pdf",
        updatedPosition
      );
    
      // ... rest of your code
    };
    

    3. User Input:

    • Ask the user to provide their preferred monitor setup (number of monitors, resolution) when opening the popup for the first time.
    • Store this information and use it to position the window more accurately.

    4. Third-Party Libraries:

    • Explore third-party libraries that might offer monitor detection capabilities. Be cautious about their reliability and security implications.

    Conclusion

    While a perfect solution to automatically determine the monitor is not available, these workarounds can offer a more user-friendly experience.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search