2011-03-17 139 views
6

我使用下面的代码在谷歌浏览器扩展程序中打开弹出式窗口,我的一个问题是,如何让弹出式窗口在中心打开用户屏幕?弹出式窗口,中央屏幕

<script> 
    chrome.browserAction.onClicked.addListener(function() { 
    var left = (screen.width/2)-(w/2); 
    var top = (screen.height/2)-(h/2); 
    chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': 440, 'height': 220, 'left': '+left+', 'top': '+top+', } , function(window) { 
    }); 
}); 
    </script> 

我也试过这样,结果没有这样的运气。

<script> 
    chrome.browserAction.onClicked.addListener(function() { 
    chrome.windows.create({'url': 'redirect.html', 'type': 'popup', 'width': 440, 'height': 220, 'left': (screen.width/2)-(w/2), 'top': (screen.height/2)-(h/2), } , function(window) { 
    }); 
}); 
    </script> 
+0

我看到的一个问题:什么是w和h?他们没有定义在任何代码段 – 2011-03-17 21:42:07

+0

@Matt S我以为他们被定义为:**'width':440,'height':220,** – itsdaniel0 2011-03-18 06:59:46

回答

13

当您在JS中看到var obj = {property: value}结构时,它是一个对象创建。在你的代码中,你试图将包含窗口属性的对象传递给chrome.windows.create()函数。

正确的代码应该是:

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

我真的不能够感谢你!谢谢 – itsdaniel0 2011-03-18 19:27:37

+0

@ itsdaniel0欢迎您:) – serg 2011-03-18 19:29:11

+1

chrome.windows.create期望'top'和'left'是整数,所以在传递参数之前请确保Math.round()。 – holmberd 2017-11-04 19:18:01

1

作为附录这个答案,如果你想要从localStorage的弹出尺寸 - 这是保存为字符串 - 这将变量转换为整数必要为弹出窗口工作。

var w = parseInt(localStorage.getItem('key')); 
var h = parseInt(localStorage.getItem('key')); 
1

如果你想在中心还具有双显示器的工作,你需要从外延得到当前窗口对象和弹出式窗口相对于该中心。像这样:

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预计,topleft的整数,因此建议在Math.round包裹这些值。

相关问题