【问题标题】:Problem with getting the tab ID in Chrome Extension在 Chrome 扩展程序中获取标签 ID 的问题
【发布时间】:2011-01-28 08:32:36
【问题描述】:

我在获取一个标签的标签 ID 并在其他标签中使用它时遇到问题。

打开了一个标签 (google.com) 我使用我的内容脚本在 google.com 上放置了一个按钮。 当单击 url 为 "cricinfo.com" 时,该按钮应创建一个选项卡。 contentscript.js

$(body).prepend('(打开)

</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>   

现在 cricinfo.com 重定向到“espncricinfo.com”,所以我希望这个 url 显示在我的原始选项卡中(即在 google.com 中)并让它显示在 textarea#follow_text 中。

要执行此操作,我需要 google.com 的 tabID,以便在 espncricinfo.com 上从 background.html 发送请求。扩展不允许在 contentscripts 中使用标签。我无法在 background.html 上使用它。

谢谢。让我知道我是否不清楚。

【问题讨论】:

  • 那么重定向的问题?您想在 textarea 中显示 cricinfo.com 或 espncricinfo.com 吗?您是为此特定网站构建此扩展程序还是应该在一般情况下工作?
  • 我想在它被重定向(或更新)后显示标签 url,即我想在 textarea 中显示 espncricinfo.com。正如您所问的,我希望它仅在父选项卡 (google.com) 上工作,并且由于我们需要来自 cricinfo 选项卡的一些信息(考虑到在重定向后我们不知道 url),它也应该在此工作。我清楚了吗
  • 怎么样 - 您创建一个新标签并记住它,然后监控该标签中发生的所有 url 更改(并在文本区域中显示这些 url)。那行得通吗?只是重定向是一个棘手的情况,很难将 http 重定向与用户重定向(点击链接)分开。
  • 我不知道检测 http 重定向的方法,chrome 扩展没有对 http 标头的完全访问权限。有看起来应该能够检测重定向的实验性 API:code.google.com/chrome/extensions/dev/…
  • 嗨,Serg,感谢您的快速回复,这是当我从 google.com 单击按钮时,它应该创建一个带有 url 的标签。我知道的 url 是 cricinfo.com,所以它作为参数并创建一个选项卡,它直接重定向到 espncricinfo.com,直到它没问题。现在我们可以在使用重定向的 url 更新选项卡时保留事件侦听器并将该信息发送到 google.com 选项卡并在那里显示。

标签: google-chrome google-chrome-extension


【解决方案1】:

嗯,这里有一些代码,但它是一种不稳定的解决方案。诀窍是,当您收听 chrome.tabs.onUpdated 时,它已经收到重定向的 url(如果没有重定向,它会收到直接的 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;
});  

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2014-07-15
    • 1970-01-01
    • 2012-06-19
    相关资源
    最近更新 更多