Pop-Up Window, Center Screen

前端 未结 3 784
感情败类
感情败类 2021-02-05 16:23

I\'m using the following code to open a pop-up window in a Google Chrome extension, my one question is, how do I get the pop-up window to open in the centre of the users screen?

相关标签:
3条回答
  • 2021-02-05 17:02

    If you want the centering to also work with a dual monitor, you'll need to get the current window object from the extension and center your popup relative to that. Like so:

    chrome.browserAction.onClicked.addListener(function() {
        chrome.windows.getCurrent(function(win) {
            var width = 440;
            var height = 220;
            var left = ((screen.width / 2) - (width / 2)) + win.left;
            var top = ((screen.height / 2) - (height / 2)) + win.top;
    
            chrome.windows.create({
                url: 'redirect.html',
                width: width,
                height: height,
                top: Math.round(top),
                left: Math.round(left),
                type: 'popup'
            });
         });
      });
    

    chrome.windows.create expects an integer for top and left, so it is recommended to wrap those values in Math.round.

    0 讨论(0)
  • 2021-02-05 17:04

    When you see var obj = {property: value} structure in JS it is an object creation. In your code you are trying to pass an object containing window properties to chrome.windows.create() function.

    Correct code should be:

    chrome.browserAction.onClicked.addListener(function() {
        var w = 440;
        var h = 220;
        var left = (screen.width/2)-(w/2);
        var top = (screen.height/2)-(h/2); 
    
        chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': w, 'height': h, 'left': left, 'top': top} , function(window) {
        });
    });
    
    0 讨论(0)
  • 2021-02-05 17:05

    As an addendum to this answer, if you want to retrieve popup dimensions from localstorage--which are saved as strings--this will convert the variables to the necessary integers for the pop-up to work.

     var w =  parseInt(localStorage.getItem('key'));
     var h =  parseInt(localStorage.getItem('key'));
    
    0 讨论(0)
提交回复
热议问题