Reputation: 1026
I've a problem getting the tab ID of a tab and using it in other tab.
There is one tab open (google.com) i've placed a button on google.com using my content script. The Button should create a tab when clicked with url as "cricinfo.com" . contentscript.js
$(body).prepend('(Open up)
</button><textarea id="followup_text"></textarea>');
chrome.extension.sendRequest({"acturl":'http://cricinfo.com',"type":""});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.greeting=="hello")
{
alert(sender.tab.url);
sendresponse({farwell:"thanks"});
}
else
sendresponse({farwell:"not recieved"});
});
});
Background.html
<script type="text/javascript" charset="utf-8">
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
chrome.tabs.create({"url":request.acturl,"selected":false},function(tab){
});
});
chrome.tabs.getSelected(null, function(tab){
chrome.extension.sendRequest(tab.id, {greeting:"hello"},function(response){console.log(response.farwell);});
}
})
</script>
Now cricinfo.com redirects to "espncricinfo.com" , So i want this url to be displayed in my original tab(i.e. in google.com) and get it displayed in the textarea#follow_text.
To perform this i want the tabID of google.com for sending request from background.html when on espncricinfo.com. The extensions doesn't allow to use tabs in contentscripts. I'm not able to use it on background.html.
Thanks. Lemme know if i'm not clear.
Upvotes: 1
Views: 6499
Reputation: 111365
Well, here is some code, but it is kind of a shaky solution. The trick is that when you listen to chrome.tabs.onUpdated
it receives redirected url already (and if there was no redirect it receives direct url).
var createdTabId = 0;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(tabId == createdTabId && changeInfo.status == "loading") {
createdTabId = 0;
//tab.url contains redirected or direct url, send it to google tab
var tabUrl = tab.url;
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.sendRequest(tab.id, {tabUrl: tabUrl});
});
}
});
chrome.tabs.create({"url":"http://cricinfo.com","selected":false},function(tab){
createdTabId = tab.id;
});
Upvotes: 3