Chrome.webstore.install调用两个回调?为什么

chrome.webstore.install calling both callbacks? Why?

本文关键字:两个 回调 为什么 webstore install 调用 Chrome      更新时间:2023-09-26

我正在尝试使用chrome.webstore.install( link, success, fail)函数内联加载谷歌Chrome扩展。

这是我的网页<head>节中的链接。

<link rel="chrome-webstore-item" 
     href="https://chrome.google.com/webstore/detail/oafp--redacted--ffencd" />

按钮在这儿。

<input type="button" class="btn btn-default" onclick="getExtension();">Go</input>

这是Javascript,它出现在关闭</body>标签之前。

 <script type="text/javascript">
    function getExtension() {
      function extensionFailed(reason) {
        console.log("extension Install Failed:", reason);
      }
      function extensionInstalled() {
        console.log("installed");
      };
      console.log("calling install");
      chrome.webstore.install(undefined, extensionInstalled(), extensionFailed());
      console.log("install returned");
    };
  </script>

单击调用getExtension的按钮,我就得到了这个事件序列,一个接一个地立即传递。

  1. "调用install"(在调用chrome.webstore.install()之前)
  2. "installed"(成功回调)
  3. "扩展安装失败,未定义"(失败回调)
  4. "安装回来了。"(呼叫chrome.webstore.install()返回后)

在中间的某个地方,异步地,我得到内联安装弹出并接受它。

我想…

  1. 失败回调应该只在失败时调用。
  2. 故障原因应该是有意义的东西,而不是undefined
  3. 成功回调应该延迟到用户接受安装。

我一定是做错了什么. ...

答案:

在这行代码中:

chrome.webstore.install(undefined, extensionInstalled(), extensionFailed());

实际上是通过在extensionInstalled()extensionFailed()中拥有()来执行函数。如果你想把它们作为回调函数传入,你可以像传入var:

一样传入函数本身。

chrome.webstore.install(undefined, extensionInstalled, extensionFailed);


函数作为变量:

注意:这不适用于您的代码,因为您在调用它们之前定义了函数,这是良好的实践。

你也可以将变量定义为函数,在我看来这只会让事情变得更加混乱。例如,这两个函数定义:

var myfunctionVar = function() {
    console.log('hello, world');
}
function myfunction() {
    console.log('hello, world');
}

您将以正常方式调用这些函数(即myfunctionVar()myfunction())。

这两个定义之间的关键区别是myfunctionVar只有在定义本身被执行后才可用,而myfunction在定义它的父函数范围内立即可用(或者一旦脚本文件被执行,如果没有父函数)。这是由于"提升",这只会使事情变得更加复杂。

在这个例子中,你不能在分配myfunctionVar()之前调用它。但是,调用myfunction()不会出现这种情况,您可以在父函数的任何地方调用它。

更多信息请看答案

函数在Javascript中比在其他语言中更复杂(也更强大!),所以希望这个答案能为你澄清一些事情。