Note 12306 compilation of the plug-in for the "empty car snatching" in the freight system-interaction between various parts of the chrome plug-in

Source: Internet
Author: User

-- Interaction between various parts of the chrome plug-in

The basic knowledge of the Chrome plug-in is not much to mention. You can get Started with any Getting Started tutorial. For example, the Overview and Getting Started tutorials provided by the official website are enough to get Started. I am also selling them now.

A plug-in is actually a collection of common web resources. resources such as js scripts, css styles, html text, images, and even dll are packaged into a file with a description file manifest. json to describe the permissions required by the plug-in and the main relationships between various resources. After the plug-in is installed in the browser, you can control the behavior of the browser to a certain extent, you can also control the dom of the web page displayed in the browser. After using dll, the plug-in can do more and provide functions beyond the browser category. For security reasons, Google officially restricts the use of dll.


Code Division in Plug-ins

The code of the Chrome plug-in is roughly divided into three parts:

A powerful plug-in is its ability to interact with web pages, which is achieved through interaction between content scripts and page DOM. With the plug-in, the dom of a page can be shared by the javascript script of the page and any content script. These scripts can modify the dom of the page, and all scripts can detect changes immediately. However, for the sake of robustness, the web page scripts and content scripts should be mutuallyIsolated. Each script runs in its own "isolated world (isolated world)", each containing a pure JavaScript environment, to ensure mutual inconsistencyImpact. Multiple isolated worlds can share the same DOM tree, but each has its own JavaScript implementation object.

For example, jQuery1.11 can be used for web pages, while jQuery2.0 can be used for content scripts. At the same time, because the plug-in may have the permission to access privileged APIs and user sensitive information, we need to confirm that scripts on the Web page cannot share these permissions. Because JavaScript objects are not shared between "isolated from the world", the web page script cannot use the shared DOM to break the normal page sandbox and access the content script or plug-in API.


Code Interaction

The plug-in can interact with pages or remote services through content scripts or cross-origin Ajax requests. Pages (including background pages) in the plug-in can access each other's DOM, or call their own defined functions. What we need to do is call chrome. extension's getViews () or getBackgroundPage () to find the corresponding page, and then we can call its function and manipulate its DOM.

For example, we have defined some common functions in the background page script background. js, such as the date Formatting Function:

// (NewDate ()). format ("yyyy-MM-dd hh: mm: ss. S ") ==> 2006-07-020. 423 // (new Date ()). format ("yyyy-M-dh: m: s. S ") ==> 2006-7-28: 9: 4.18 Date. prototype. format = function (fmt) {var o = {"M +": this. getMonth () + 1, // month "d +": this. getDate (), // Day "h +": this. getHours (), // Hour "m +": this. getMinutes (), // minute "s +": this. getSeconds (), // second "q +": Math. floor (this. getMonth () + 3)/3), // quarter "S": this. getMillise Conds () // millisecond}; if (/(y + )/. test (fmt) fmt = fmt. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length); for (var k in o) if (new RegExp ("(" + k + ")"). test (fmt) fmt = fmt. replace (RegExp. $1, (RegExp. $1. length = 1 )? (O [k]) :( ("00" + o [k]). substr ("" + o [k]). length); return fmt ;}

In the initialization script initPopup. js in the pop-up box, we can reuse the Code as follows:

var bg =chrome.extension.getBackgroundPage();Date.prototype.Format= bg.Date.prototype.Format;

Content scripts can be viewed as part of a Web page, rather than a part of a plug-in. Therefore, content scripts can modify the dom of a Web page, but cannot modify the dom of a background page, you cannot call special methods such as getBackgroundPage.

It is worth noting that:

  • Content scripts and web pages run in different sandboxes. The JS methods of the two cannot be called each other.
  • Content scripts can interact with other parts of the plug-in indirectly, which is completed through message sending and receiving.


Message transmission

Based on security considerations, the JavaScript environment of content Scripts has no privilege, just as it affects web pages. This means that if you want to access the plug-in API from the content script, you must communicate with the plug-in the privileged part of the content script and plug-in, this method is "message passing. Message transmission allows communication between all parts of the plug-in. We usually want to communicate between the content script and the background page, but any pages of the plug-in can communicate with each other. If we know the unique ID of other plug-ins, we can even send messages to other plug-ins.

Here is a simple example:

The initialization script in the pop-up box contains a saveParam method, which obtains two values in the pop-up box and stores them in the browser's synchronous storage. Then, set the button with id btn to click the event handler function, call the Save method, and send a message to other parts of the plug-in:

         functionsaveParam(){                   _d = $('#aidForm#zcrq').val(), _hqhw = $('#aidForm #hqhw').val();                   chrome.storage.sync.set({'zcrq':_d,'hqhw':_hqhw});         }                function getSavedParam(callBack){                   chrome.storage.sync.get(function(o){                            _d = o.zcrq, _hqhw =o.hqhw;                            if(null !=callBack){                                     callBack();                            }                   });         }                $('#aidForm #btn').click(function(e){                   saveParam();                   chrome.extension.sendRequest({'msg':'openpage','zcrq':_d, 'hqhw':_hqhw,                            'url':'xxxxxx'},                            function(data) {});                   e.preventDefault();         });

Then, in the script or content script on the background page, we can register the message listening method to process the message content accordingly:

         chrome.extension.onRequest.addListener(function(request,sender, sendResponse){                   if(request.msg== 'openpage'){                            _d= request.zcrq, _hqhw = request.hqhw;                            chrome.tabs.create({'url':request.url,'active':true});                   }         });

Because content scripts can only call chrome. some of the privileged methods in the extension object, chrome. the privileged method of the tabs object cannot be called. However, the content script can send messages to other parts of the plug-in through the message transmission mechanism, such as the background page script, so that the latter can complete some work. Of course, if you are interested, you can use the HTML5 window. postMessage method in combination with the window. addEventListener method to transmit messages in other part of the code of the plug-in.


Best practices

To sum up, the best practices for chrome plug-in development may be:

The background page script maintains the main logic and methods of the plug-in. The content script interacts directly with the web page, and the pop-up box, options, and other pages are used as an aid, the content script interacts with other scripts of the plug-in through the message transmission mechanism to achieve the integration of various functions of the plug-in.

That's all! Hope to help you.

In addition, there are two words marked with strikethrough.Isolated","Impact"It turns out to be" duli "and" chongtu "respectively. When I published my post, I was prompted" * Sorry, this article contains sensitive words. Please check and release it again .", Failed to save, delaying the publication, shame, shame, and shame of the Article !!! 10 thousand alpaca in my heart!

 

Related Article

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.