【问题标题】:Chrome extension problem getting tab urlChrome 扩展程序获取标签页 url 的问题
【发布时间】:2011-07-08 22:17:01
【问题描述】:

我不擅长 JS,我遇到了一些 - 我希望 - 愚蠢的问题,我没有在我的代码中看到......如果你们能帮助我,我真的很感激。

我的扩展对当前标签的 URL 做了一些处理。在我的背景页面上使用 onUpdate 事件可以正常工作,在变量上设置选项卡的 URL,然后我在弹出窗口中使用它。

问题是,如果用户开始,选择不同的选项卡,而不更新 URL,我的事件将不会再次被触发......所以我现在也在监听 onSelectionChanged 事件。

问题是 onSelectionChanged 事件的参数中没有“tab”对象,所以我不能要求 tab.url 属性。

我尝试使用 chrome.tabs.getCurrent() 方法,但显然我做错了什么......并且我达到了我的 - 非常少 - 知识的极限。 p>

这是代码,如果你们能看一下并指出正确的方向,我将不胜感激。

<script>
var tabURL = '';

var defaultURLRecognition = [ "test" ];

  // Called when the url of a tab changes.
  function checkForValidUrl(tabId, changeInfo, tab) {

            //THIS IS WHAT'S NOT WORKING, I SUPPOSE
    if (tab==undefined) {
        chrome.tabs.getCurrent(function(tabAux) {
            test = tabAux;
        });
    }
            //

    // If there's no URLRecognition value, I set the default one
    if (localStorage["URLRecognition"]==undefined) {
            localStorage["URLRecognition"] = defaultURLRecognition;
        };
    // Look for URLRecognition value within the tab's URL
    if (tab.url.indexOf(localStorage["URLRecognition"]) > -1) {

    // ... show the page action.
      chrome.pageAction.show(tabId);
      tabURL = tab.url;

    }
  };

  // Listen for any changes to the URL of any tab.
  chrome.tabs.onUpdated.addListener(checkForValidUrl);
  // Listen for tab selection changes
  chrome.tabs.onSelectionChanged.addListener(checkForValidUrl);

</script>

【问题讨论】:

    标签: google-chrome-extension browser-tab


    【解决方案1】:

    我会这样做:

    function checkForValidUrl(tab) {
        //...
    }
    
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
        if(changeInfo.status == "loading") {
            checkForValidUrl(tab);
        }
    });
    
    chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo){
        chrome.tabs.getSelected(null, function(tab){
            checkForValidUrl(tab);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多