2013-05-12 16 views
5

新しいタブを開くpopup.htmlのボタン付きChrome拡張機能を使用しています。新しいタブのリンク先URLには、現在の(元の)タブの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}); 
    }); 

}) 

新しいタブが完全に開かれますが、URLはhttp://www.mydestination.com/index.php?url=undefined(URLです=未定義)。

私はmanifest.jsonを右権限を保持数える:適切に運ばURLを取得する方法について

{  
"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" 
} 
} 

任意の手掛かりを?

+0

、「タブ」は、実際にクリックイベントになり、あなたは 'のaddEventListener(「クリック」、機能(EVT、タブを){意味いけない...' – 1337holiday

答えて

4

問題は現在のタブがあなたのクロムポップアップだということです。この場合、有効なURLはありません。 あなたのタブを選択する必要があります。これを行うには、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

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 –

+0

@WaleryStrauch haha​​、それはかなり面白いです – BeardFist

+0

皆さんは同期しています! – Lionel