2011-03-17 140 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包裹這些值。

相關問題