0

我想创建一个Chrome扩展可以解释通过键盘给出的命令。 此扩展的目的是,如果用户按下ALT + A然后在警报框中显示的标签ID流序列在Chrome扩展

Manifest File : 
{ 
    "manifest_version": 2, 

    "name": "Toggle", 
    "description": "This App ", 
    "version": "1.0", 

    "background": { 
    "persistent": true, 
    "scripts": ["TabBackGround.js"] 
    }, 

    "commands": 
    { 
     "toggle" : 
     { 
      "suggested_key": { 
       "default": "Alt+A", 
       "mac": "Command+Shift+Y" 
      }, 
      "description" : "Toggle the tabs" 
     } 
    }, 

    "permissions": ["tabs", "background"], 

    "browser_action": { 
    "default_title": "This App will help to toggle through tabs on which videos is running", 
    "default_icon": "hello.png" 
    }  
} 

TabBackGround.js

var globalId; 

chrome.commands.onCommand.addListener(function(command) { 
    if (command == "toggle") 
    { 
     alert ("Command Resolved."); 
     var queryGetTabs = chrome.tabs.query({active: true, currentWindow: true}, function(arrayOfTabs) { 

      alert ("Function Executed."); 

      var activeTab = arrayOfTabs[0]; 
      var activeTabId = arrayOfTabs[0].id; 
      globalId = activeTabId; 
    }); 

     alert ("Pressed Toggle : " + globalId); 
    } 
}); 

输出:命令解决。 按下切换 函数中执行。 我想了解什么是JavaScript执行的流程。按下切换按钮之前不应该执行功能声明。

回答

1

大多数浏览器的API是异步的性能/响应的原因。你看到的是这样的:

/* Some code that will execute first */ 
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    /* Some code that will execute last */ 
} 
/* Some code that will execute second */ 

执行chrome.tabs.query不会立即做任何事情(并且不会返回任何东西,顺便说一下),而是要求Chrome浏览器查询标签时,它可以,然后执行回调。顺便说一句,这就是为什么它被称为“回调”的原因。

其他的方式来看待它:你注册回调为“工作完成”的事件处理程序。每当它实际完成时。

因此,您的函数将在调度此操作后继续,并且不能使用回调函数的任何结果。如果你需要异步代码,你需要链接你的电话:

/* Some code that will execute first */ 
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    /* Some code that will execute second */  
    chrome.someOtherApiFunction(function() { 
    /* Some code that will execute last */ 
    }); 
} 
+0

有没有办法让查询调用同步? – 2014-09-30 06:48:12

+0

总之,没有。这个调用实际上并不是在JavaScript中发生,而是在Chrome的本地代码中发生,我认为这些代码与页面的JS不同步。如果您想要一些更好的工具来处理异步代码,您可以查看[Promises](http://www.html5rocks.com/en/tutorials/es6/promises/)。尽管在这里可能是一个矫枉过正的问题。 – Xan 2014-09-30 06:52:22

+0

好感谢您的回复。我了解同步和异步呼叫之间的区别,并相应地对代码进行了更改。我正在尝试显示当前活动选项卡的选项卡标识和选项卡URl。 – 2014-10-01 04:31:27