Chrome扩展程序中的流程序列

时间:2014-09-29 09:29:14

标签: javascript google-chrome-extension google-chrome-devtools

我想创建一个chrome扩展,它可以解释通过键盘给出的命令。 此扩展的目的是,如果用户按下ALT + A,则在警告框中显示选项卡ID

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中的执行流程是什么。在按下切换之前,不应该执行Function语句。

1 个答案:

答案 0 :(得分:1)

出于性能/响应原因,大多数Chrome 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 */
  });
}