--chrome The various parts of the interactive plugin
The basics of chrome plugins are not much to say. Just find a beginner tutorial to get started, such as the official overview and Getting Started tutorial enough to start, the author is now learning to sell.
A plugin is actually a collection of common Web resources that package resources such as JS scripts, CSS styles, HTML text, pictures, and even DLLs into a single file. And with a description of the document Manifest.json, to explain the permissions required by the plug-in and the basic relationship between the various resources. After the plugin is installed in the browser, it is possible to control the browser's behavior to a certain extent, as well as to control the DOM of the Web page displayed in the browser. And after using the DLL. There are a lot of other things that plug-ins can do. Ability to provide functionality beyond the browser category. For security reasons, Google is already restricting the use of DLLs.
Division of code in plugins
The code for the chrome plugin is broadly divided into three parts:
- Background page (Background page): Most plugins contain an invisible background page that is used to maintain the main logic of the entire plugin.
- UI page: A plugin can also contain some UI pages. Contains pop-up pages (pops up when clicked on the plugin icon), Configuration page (opens when the plugin is configured), and overlay pages (one plug-in can overwrite one of the three bookmarks management pages, history pages, or new tabs).
- Content script: Assume that a plugin needs to interact with a Web page. The plugin will need to use the content script.
One of the strengths of the plug-in is its ability to interact with the Web page, which is accomplished through the interaction of the content script with the page DOM.
With the plugin. The DOM of a page can be shared by JavaScript scripts of the page itself and random content scripts. These scripts can change the DOM of the page, and all of the scripts can immediately perceive changes, but for the sake of robustness, The script and content scripts of the Web page should be isolated from each other .
Each script executes in its own "isolated world", each of which includes a pure JavaScript environment. Ensure that they do not affect each other.
Multiple "isolated worlds" can share the same DOM tree. But they have their own corresponding JavaScript implementation object.
For example, a Web page can use the jQuery1.11 version number. Our content script can use the jQuery2.0 version number, and the use of the two does not affect each other. At the same time. Because plug-ins may have privileged APIs and access to user-sensitive information, we need to confirm that the script for the Web page cannot share these permissions. Because JavaScript objects are not shared between "isolated worlds", it is not possible for a Web page's script to break through the normal page sandbox with a shared dom to access content scripts or plug-in APIs.
The
interaction of each part of the code
plug-ins can interact with pages or remote services through content scripting or cross-domain AJAX requests.
each page in the plugin (including the background page) can visit each other's DOM . Can also invoke each of its own defined functions. all we need to do is call Chrome.extension's getviews () or getbackgroundpage () to find the corresponding page, and then be able to invoke its function and manipulate its DOM.
For example, we defined some common functions in the background page script background.js, such as the date formatter function:
(Newdate ()). Format ("Yyyy-mm-dd hh:mm:ss. S ") ==> 2006-07-0208:09:04.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 (),// Sub "s+": This.getseconds (),//sec "q+": Math.floor ((This.getmonth () +3)/3),//quarterly "s": this.getmilliseconds ()//milliseconds }; 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]):(("XX" + o[k]). substr (("" + o[k]). length)); return FMT; }
in the init script initpopup.js of the popup box. We can reuse code like this:
var bg =chrome.extension.getbackgroundpage ();D ate.prototype.format= BG. Date.prototype.Format;
Content scripts can be seen as part of a Web page. Rather than part of the plugin , so the content script can change the DOM of the Web page, but not the DOM of the background page, that is, the privileged methods such as getbackgroundpage cannot be called.
It is worth noting that:
- The content script executes in a different sandbox than the Web page. There is no way to invoke each other between the two JS methods.
- The content script interacts indirectly with the rest of the plug-in, and the interaction is completed by sending and receiving the message.
Message Delivery
For security reasons, the JavaScript environment for content scripting is not privileged. Just like the Web page he was affecting.
This means that if you want to access the plug-in API from a content script, you need a way to communicate with the privileged parts of the plug-in in the content script, which is "message passing". Messaging agrees to communicate between the parts of the plug-in. Usually we want to communicate between the content script and the background page, except that the plug-in's random pages are able to communicate. Suppose you know the unique ID of the other plug-in. We are even able to send messages to other plugins.
Here's a simple example:
A Saveparam method is included in the initialization script for the popup box. Responsible for getting the two values in the pop-up box and then storing them in the browser's sync storage.
Then, set the Click event handler for the button with the ID btn. Call the Save method and send a message to the other parts of the plugin:
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 background page script or content script, we are able to register the message listener method. To handle the corresponding message content:
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 the content script can only invoke a subset of the privileged methods in the Chrome.extension object, the privileged method of the Chrome.tabs object in the example above cannot be called, but the content script can send messages to other parts of the plugin through the messaging mechanism. such as the background page script, let the latter help it complete part of the work . Of course, if interested, the other parts of the plug-in code can also use the HTML5 Window.postmessage method, with the Window.addeventlistener method for message delivery.
Best Practices
As mentioned above, the best practices for chrome plug-in development may be:
The Background page script is responsible for maintaining the main logic and methods of the plug-in, the content script is responsible for direct interaction with the Web page, popup boxes and options and other pages as auxiliary, the content script and the plug-in's other scripts through the message passing mechanism to interact. In order to achieve the integration of various parts of the plug-in.
that ' s all! Hope to help everyone.
Another: The text in a paragraph has marked the deletion line two words " isolate ", " influence " originally each is "Duli" and "Chongtu", published when unexpectedly hint "* Sorry, the article includes sensitive words, please check and publish again."
”。 Save unsuccessful, delay the publication of the article, ashamed. Shame, shame!
!
! 10,000 llamas in the heart!
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Remember 12306 freight system "snapped empty" writing plug-ins--chrome the various parts of the interactive plugin