从网站按钮运行chrome应用程序

Has*_*han 1 javascript google-chrome web google-chrome-app

我需要从网页按钮点击启动Chrome应用程序.我找到了以下资源,'

这建议使用external_connectableurl_handlers,但似乎不起作用.有没有正确的方法可以通过调用chrome app extension id点击网页上的按钮来启动Chrome应用程序?

我是这个领域的新手,非常感谢你们专家给予的任何帮助:)

PS

我在网页上单击按钮时尝试了以下命令,

chrome.management.launchApp('app id');

这导致了错误Uncaught TypeError: Cannot read property 'launchApp' of undefined.

Has*_*han 6

我找到了如何实现这一目标,其他人遇到了这个问题.

  • 在您的网页上点击按钮,例如,包含以下代码,

                                                     //data passed from web to chrome app
    chrome.runtime.sendMessage('your_chrome_app_id', { message: "version" },
        function (reply) {
            if (reply) {
                if (reply.version) {
                    //log the response received from the chrome application
                    console.log(reply.version);
                }
            }
        }
     );
    
    Run Code Online (Sandbox Code Playgroud)
  • 在您的chrome应用程序manifest.json中定义externally_connectableurl/urls,如下所示,

     {
      "name": "App name",
      "description": "App Desc",
      "version": "1",
    
      ...
    
      "externally_connectable": {
        "matches": ["*://localhost:*/"]
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 在您的应用程序background.js中设置一个侦听器,当从网页发送消息时调用该侦听器,如下所示,

    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if (request) {
          if (request.message) {
            if (request.message == "version") {
    
              //my chrome application initial load screen is login.html
              window.open('login.html');
    
              //if required can send a response back to the web site aswell. I have logged the reply on the web site
              sendResponse({version: '1.1.1'});
            }
          }
        }
        return true;
      });
    
    Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :)