Chrome plugin: Starting a local app (Native messaging)

Source: Internet
Author: User
Tags button type log4net

Chrome plugin: Start local app (Native messaging) www.MyException.Cn share in: 2014-08-01 views: 3 timesChrome Plugin: Launch local app (Native messaging)

Recently encountered a new problem, need to use chrome plug-ins, from one of our web site to launch a our local C # application, while the application value to do different operations.

Record the process here to find out later

First we need to create a new Google plugin that contains 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 website 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>

The premissions is very important, he said that our plug-in on what conditions to run, "nativemessaging" means to allow this method to be called in this plugin

"XXX" Fill in the URL you want to load

"XXX" in "content_scripts" is the script that runs our interaction with the interface 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 very important.

Chrome.runtime.onMessage.addListener

And

Connecttonativehost

Let's take a look at the first method

is a response event that calls the Connecttonativehost method and passes in the data when a message of type "launch" is received.

Com.my_company.my_application

This is what we need to register in Regestry and native messaging after the name will be mentioned.

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 simply, response to a page of the event "Mycustomevent", while publishing a message to our background file background.js, this message contains the message labeled "Launch" and we want to pass the value Evt.detail

For information on content Script, see 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

------------------------------------- Split line -------------------------------------

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

<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 run 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 You can open developer mode in chrome and load our previous plugin package)

After completing this step we need to include the Google project in the Windows registry as follows:

Run, Regedit, hkey_current_user->software->google->chrome-> create a new item called Nativemessaginghosts- > Create a new item called Com.my_company.my_application, and the default value in this key is set to the location of our Native Messaging c:\\native\\ Manifest.json

So we're done with the nativemessaging setup.

------------------------------------- I'm a split line -------------------------------------

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

Build a simple Web page that reads as follows

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

There is a simple button, this button will start the method, create a new "Mycustomevent" event, accompanied by the information we want to preach, and publish the event. This allows the content.js in our plugin to receive and respond to this event!

------------------------------------- I'm a split line -------------------------------------

Let's take a look at the C # program and do a very simple program and put it in the

C://myapp.exe here

In main we can add the following method, using Console.openstandardinput This we can receive the value from the page to our application and do some of the actions we want, here we use a log4net to record the operation of our program

[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 we added to the page and 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

If 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'm not going to repeat it here.

4 floor Yhdufei yesterday 16:10
Thank you, sincerely thank you, personally give me debugging procedures, finally can.
3 floor qq_18649531 yesterday 17:49
can you put a sample code on it? Very much looking forward
Re: nicolas_008 yesterday 22:57
reply qq_18649531n has added the test code for the C # section
2 floor Yhdufei yesterday 17:44
This warrior, I follow the step by step, but how can not start the application. Can add your QQ, guide brother a bit ... I looked for this information for a long time, and finally found you this detailed introduction. 369569334, kneel, Xie! Pay also!
1 floor u011441796 yesterday 13:53
It
's a good look.

Chrome plugin: Start a 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.