2013-05-12 190 views
5

我在popup.html中使用了一個Chrome擴展,並在其中打開了一個新選項卡。新選項卡的目標網址將當前(原始)選項卡的URL保存爲參數。Chrome擴展程序tab.url undefined

例如:從http://stackoverflow.com/發射時,新標籤應該有一個像http://www.mydestination.com/index.php?url=http://stackoverflow.com/

這裏的URL是我的JS:

document.addEventListener('DOMContentLoaded', function (tab) { 

    document.getElementById('button').addEventListener("click", function(tab) { 
     chrome.tabs.create({url: 'http://www.mydestination.com/index.php?url=' + tab.url}); 
    }); 

}) 

新的標籤是完全打開的,但是網址是http://www.mydestination.com/index.php?url=undefined(URL =未定義)。

我認爲對於manifest.json持有正確的權限:

{  
"manifest_version": 2, 
"name": "My project", 
"version" : "1.7", 
"browser_action": { 
    "default_icon" : "img/icon.png", 
    "default_title" : "My project", 
    "default_popup": "html/main.html" 
}, 
"permissions": [ 
    "tabs" 
], 
"icons": { 
    "16": "img/icon.png" 
} 
} 

如何獲取URL運輸不當任何線索?

+0

哇等待, 「標籤」 實際上是click事件,不要你的意思'的addEventListener( 「點擊」,函數(EVT,標籤){...' – 1337holiday 2013-05-13 02:20:28

回答

4

問題是當前標籤是你​​的chrome彈出。在這種情況下,您沒有有效的網址。 你必須選擇你的標籤。要做到這一點,你可以使用chrome.tabs.query。活躍選項卡中選擇當前窗口:

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('button').addEventListener("click", function() { 
     chrome.tabs.query({ 
      'active': true, 
      'windowId': chrome.windows.WINDOW_ID_CURRENT 
     }, function (tabs) { 
      chrome.tabs.create({ 
       url: 'http://www.mydestination.com/index.php?url=' + tabs[0].url 
      }); 
     }); 
    }); 
}); 
+0

感謝百萬分之一,這就像一個魅力! – Lionel 2013-05-13 05:31:50

1

問題在於,當它與事件無關時,通過tab作爲參數。儘管某些chrome.* apis確實包含了一個製表符對象作爲參數,但您不能只是像這樣添加它,並期望它具有所需的信息。你可以這樣做:

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('button').addEventListener("click", function() { 
    chrome.tabs.query({active:true, currentWindow:true},function(tab){ 
     // Just doing it like this to make it fit on the page 
     var newUrl = "http://www.mydestination.com/index.php?url=" + tab[0].url; 
     chrome.tabs.create({url:newUrl}); 
    }); 
    }); 
}); 
+0

近同樣的答案在同一時間:D – 2013-05-12 21:05:31

+0

@WaleryStrauch哈哈,這很有趣 – BeardFist 2013-05-12 21:07:30

+0

你們同步! – Lionel 2013-05-13 05:32:26