Chrome Gadget: Launch local app (Native messaging)

Source: Internet
Author: User

Recently encountered a new problem. You need to use the chrome plugin to launch a C # app from one of our local sites and perform different actions with this application value.

The process of resolving is documented here. To find later


First we need to create a new Google plugin that includes three files

Manifest.json (name cannot be changed, build plugin must file),background.js(file name can be changed, background file),content.js(Content script file is responsible for interacting with Site page)

First, let's take a look at the manifest.json file.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >{"name": "Fastrun", "Version": "1.0.1", "description": "Launch APP", "background": {"Scripts": ["Background.js"]}, "Permissions": ["Nativemessaging", "tabs", "http://xxx/*"], "content_scripts": [    {      "matches": ["http://xxx/* "],      " JS ": [" Content.js "]    }]," Minimum_chrome_version ":" 6.0.0.0 "," manifest_version ": 2}</span>

Inside the premissions is very important, he said that our plug-in under what conditions, "nativemessaging" represents to be in this plugin to agree to invoke such a method

"XXX" Fill in the URL you want to load

"XXX" in "content_scripts" means the script under which we interact with the interface is performed under what Web page.


Take a look at the background file.

Background.js

var port = null; Chrome.runtime.onMessage.addListener (  function (request, sender, Sendresponse) {     if (Request.type = = "Launch" ) {       connecttonativehost (request.message);    


There are two methods in this file that are important

Chrome.runtime.onMessage.addListener

And

Connecttonativehost

Take a look at the first method first.

is a response event. When a message of type "launch" is received, the Connecttonativehost method is called and the data is passed in.

Com.my_company.my_application

This is what we need to register later in the name of Regestry and native messaging.

Runtime.connectnative This method to connect our native messaging and then use PostMessage to send us the information we want to our local application

Of course, here we can replace the sendnativemessage directly to the local application pass the value see

Https://developer.chrome.com/extensions/runtime#method-connectNative

We're looking at Contentscript: content.js This file

<span style= "Font-family:simsun;" ><span style= "FONT-SIZE:18PX;" >var launch_message;document.addeventlistener (' mycustomevent ', function (evt) {chrome.runtime.sendMessage ({type : "Launch", Message:evt.detail}, function (response) {  Console.log (response)});}, False);</span>< Strong></strong></span>
very easy, in response to a page of events "Mycustomevent", at the same time to publish a message to our background file Background.js, this message includes the message labeled "Launch" and we want to pass the value Evt.detail

about Cont ent Script information is described in Https://developer.chrome.com/extensions/content_scripts

Our Google plugin section is ready to go here.

Don't forget to open developer mode and load this plugin in the chrome plugin

------------------------------------- Cutting line -------------------------------------


We're looking at the Native Messaging section we're going to build a JSON file. I'm also called Manifest.jsonhere (the name can not be this) exists in my local c:/native folder

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >{"name": "Com.my_company.my_application", "description": "Chrome sent message to native app.", "path": "C:\\ MyApp.exe "," type ":" Stdio "," Allowed_origins ": [" chrome-extension://ohmdeifpmliljjdkaehaojmiafihbbdd/"]}</span >

Here we define the name of Native Messaging, which defines the local application we want to execute in path, and the long string of characters in Allowed_origins is the ID of our plugin that can be seen from the Google Chrome plugin after the plugin is installed (install plugin Ability to open developer mode in chrome and load our previous plug-in packages)


After this step we need to add the Google Project details to the Windows registration form as follows:

Hkey_current_user->software->google->chrome-> , Regedit---Create a new item called Nativemessaginghosts- > Create a new item called Com.my_company.my_application, at the same time the default value is set to the location of our Native Messaging c:\\native\\ Manifest.json


So we're finished. nativemessaging Settings

------------------------------------- I'm a cutting line --------------------------- ----------

Let's take a look at how this plugin interacts with our site.

Build a simple Web page, such as the following

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><! DOCTYPE html>

There is a simple button in it, this button will start the method, create a new event called "Mycustomevent", the same time with the information we want to preach, and announce the event. This allows the content.js in our plugin to receive and respond to this event!

------------------------------------- I'm a cutting line -------------------------------------

We finally look at the C # program, do a very easy program, put in the

C://myapp.exe here

[Assembly:log4net. Config.xmlconfigurator (Watch = true)]namespace myapp{static class program {public static log4net. ILog log = log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod ().        DeclaringType); [STAThread] static void Main (string[] args) {if (args.                Length! = 0) {String chromemessage = Openstandardstreamin (); Log. Info ("--------------------My application starts with Chrome Extension message:" + chromemessage + "---------------------        ------------"); }} private static string Openstandardstreamin () {////We need to read first 4 bytes for Leng            Th information Stream stdin = Console.openstandardinput ();            int length = 0;            byte[] bytes = new Byte[4]; Stdin.            Read (Bytes, 0, 4);            Length = System.BitConverter.ToInt32 (bytes, 0);            string input = ""; for (int i = 0; I < Length i++) {input + = (char) stdin.            ReadByte ();        } return input; }    }}


Click on the button that we added on the page, and then check the log file:


2014-07-30 09:23:14,562 [1] INFO myapp.program----------------------------------------My application starts with Chrome Extension message: {"message": "Im Information"}---------------------------------




The final picture summarizes the process

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvtmljb2xhc18wmdg=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Suppose you want to install this plugin when installing our local software, we need to post our plugin to the Chrome Web store for details https://developer.chrome.com/extensions/external_extensions

I will not repeat

Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Chrome Gadget: Launch local app (Native messaging)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.