Chrome plug-in development

Source: Internet
Author: User

Written at the beginning: An interesting UI interface, code implementation, and browsing speed. It is quite tempting for people who have been using browsers for more than 10 hours a day to customize their own browsers.

Getting started
1: currently, the standard release version of chrome plug-in extension is not supported, but some messages are developed immediately. This is not a problem for us. 4.0 is in use.
2: Create a necessary folder with an arbitrary name for storing the required files. After development, you can submit it through chrome packaging.
3: manifest. JSON file, which stores the description information. It can also be understood as the general entry for running the plug-in and is defined in JSON format.
{
"Name": "My first extension", // program name
"Version": "1.0", // version
"Description": "The first extension that I made.", // description
"Browser_action": {// operations on the browser
"Default_icon": "icon.png" // icon
},
"Permissions": [// permission, used to define the required network resources
"Http://api.flickr.com /"
]
}
4: You can add features in browser_action.
"Popup": "popup.html" // specifies the action triggered after a button is clicked,

5: the pop-up HTML extension file is compiled in the pop-up window. js and CSS can be used. Note that HTML must be included in the folder.
In particular, HTML5 standard elements can be used.
Files contained in the plug-in
1: manifest file, 2: Any HTML file, 3: Javascript file, 4: Image File
After packaging, it will be compressed into a zip file in special format with the extension. CRX

Background page: The main logic used to save the plug-in,
The logic of the plug-in is divided into page action and browser action. The js of the background.html file simultaneously controls the two actions.

Action, which can be understood as an action, that is, the behavior displayed by the browser, just like a pop-up window.
Browser_action includes a tooltip, a badge, and a popup.

You can register the required browser action in the manifest file, where default_icon is required, and others are optional (OR)

UI
Icon: Most image formats are supported. We recommend that you use a 19-pixel square image. You can set it to default_icon in the manifest file or call the seticon () method.
Tooltip: Set the default_title attribute of manifest, or call the settitle () method.
Badge: used to display characters under the icon. The number of words is limited to four characters. You can use setbadgetext () and setbadgebackgroundcolor () to set the content and background color.
Popup: the pop-up window is displayed. The popup attribute of browser_action is defined in the manifest file.

Common Methods of chrome. browseraction, where parameters use JSON objects. For details, see the corresponding API query key.

Setbadgebackgroundcolor: Set the background color of badge.
Chrome. browseraction. setbadgebackgroundcolor (Object details );

Setbadgetext: badge content
Chrome. browseraction. setbadgetext (Object details)

Seticon: Set the icon
Chrome. browseraction. seticon (Object details)

Shettitle: Set tooltip
Chrome. browseraction. settitle (Object details)

Browseraction event
Chrome. browseraction. onclicked. addlistener (function (Tab tab) {...}); // triggered when the icon is clicked
// The parameter here is more of a type than JS

2: Provide the corresponding options page for the plug-in, add the corresponding options_page in the manifest file: option, use HTML
"Options_page": "options.html ",

The required HTML can be a complete HTML document containing the required HTML elements.

Override interface: used to replace the new tab interface. It is different from the default Interface and is registered in the manifest file.
"Chrome_url_overrides ":{
"Newtab": "newtab.html"
},

Page Actions: used to display icons on a specified page
"Page_action ":{
"Default_icon": "icons/foo.png", // required
"Default_title": "Do action", // optional; shown in tooltip
"Popup": "popup.html" // optional
},
Difference browser action, page action does not contain badges, but can control whether the page action is displayed, by calling show () and hide () Methods

The browser recommendations also apply to Page Actions;

Common page action Methods
Hide;
Chrome. pageaction. Hide (integer Tabid)
Seticon
Chrome. pageaction. seticon (Object details)
Settitle
Chrome. pageaction. settitle (Object details)
Show
Chrome. pageaction. Show (integer Tabid)
Events, similar to browser Action events
Onclicked
Chrome. pageaction. onclicked. addlistener (function (Tab ){...});

Themes skin
It is also packaged as a standard extension component, but does not contain the corresponding JS and HTML code. It is set only in the main manifest. JSON file.
{
"Version": "2.6 ",
"Name": "camo theme ",
"Theme ":{
"Images ":{
"Theme_frame": "images/theme_frame_camo.png ",
"Theme_frame_overlay": "images/theme_frame_stripe.png ",
"Theme_toolbar": "images/theme_toolbar_camo.png ",
"Theme_ntp_background": "images/theme_ntp_background_norepeat.png ",
"Theme_ntp_attribution": "images/attribution.png"
},
"Colors ":{
"Frame": [71,105, 91],
"Toolbar": [207,221,192],
"Ntp_text": [20, 40, 0],
"Ntp_link": [36, 70, 0],
"Ntp_section": [207,221,192],
"Button_background": [255,255,255]
},
"Tints ":{
"Buttons": [0.33, 0.5, 0.47]
},
"Properties ":{
"Ntp_background_alignment": "bottom"
}
}
}

Default skin, which can be viewed through the link below
Http://src.chromium.org/viewvc/chrome/trunk/src/chrome/browser/browser_theme_provider.cc

In tints, the hue-saturation-Lightness gray saturation brightness is used to set the values between 0 and 1.

Browser Interaction: browser Interaction
Bookmarks, events, tabs, windows, etc.

Bookmarks, favorites, which can be created, organized, and managed
Set permissions: in the manifest File
"Permissions ":[
"Bookmarks"
],
The favorites folder stores objects in the form of tree, which mainly uses the bookmarktreenode object for access. common attributes include index, title, and URL.

Note: The tree structure itself is relatively cumbersome. You can use the following method for access.
Function btnclick (){
Chrome. bookmarks. gettree (function (ASS ){
Console. Log (ass [0]. Children [0]);
For (OBJ in ass [0]. Children [0]. Children ){
Console. Log (ass [0]. Children [0]. Children [OBJ]. Title );
}
})
}
We recommend that you first check the Debug Method (PS: relatively cumbersome, but it is easier to view the object structure with console. Log)

The ID is also auto-increment, starting from 0.
Common Methods
Create, get getchildren gettree move Remove removetree search update
Common events

Common events
Onchanged onchildrenreordered oncreated onmoved onremoved

Example:
Chrome. bookmarks. onmoved. addlistener (...)
Chrome. bookmarks. gettree (...) // For details, refer to the API

Event event example
Chrome. Tabs. oncreated. addlistener (function (Tab ){
Appendtolog ('tabs. oncreated --'
+ 'Window: '+ TAB. windowid
+ 'Tab: '+ TAB. ID
+ 'Index: '+ TAB. Index
+ 'Url: '+ TAB. url );
});
Attach the corresponding permissions permission tabs
All operation methods of the event:
Void addlistener (function callback (...))
Void removelistener (function callback (...))
Bool haslistener (function callback (...))

Tabs is used to control each label, and chrome. tabs is called
Common Methods:
Capturevisibletab connect create detectlanguage executescript get getallinwindow getselected insertcss move Remove sendrequest update

Common events:
Onattached oncreated ondetached onmoved onremoved onselectionchanged onupdated

Multiple windows in Windows chrome

Optional windowid parameter in method call. The default value is the current window.

Call object: chrome. Windows

Common method: Create get getall getcurrent getlastfocused remove update
Common events: oncreated onfocuschanged onremoved

Background pages, registered in the manifest file, used to save long-running scripts. Running in the process where the plug-in is located is mostly used for functions similar to daemon threads and for status updates.
How to obtain the page:
VaR views = chrome. extension. getviews (); // The obtained array. The specified view is the JS windows object through loops or indexes. However, only the HTML elements configured in manifest are limited here.
"Background_page": "background.html ",

Content scripts is used to script the content of a specified page.
You also need to register in the manifest File
"Content_scripts ":[
{
"Matches": ["http://www.google.com/*"],
"CSS": ["mystyles.css"],
"JS": ["jquery. js", "myscript. js"]
}
],

Common attributes:
Matches, a string array, which is used to inject a specified URL page according to the specified matching mode.
JS: the specified script file will be injected to the correct page. Optional.
CSS: the CSS to be embedded. Optional.
Run_at: used to set the time for injection. The default value is document_idle. Other values include document_start, document_end,
All_frames: the default value of Boolean is false.

You can refer to the official documentation for the usage method. However, you cannot simply replace the function with the same name to inject and replace events. However, you can directly use document. getelementbyid obtains and modifies the specified Dom component.
Scope issue: the original variables cannot be accessed. If you need to replace them, you need to complete the event and re-declare and replace the variables.
Special scope: for injection code, there will be a closed scope that will not conflict with the original, but the DOM element of the page can be modified.

Example of adding in-plug-in images to page elements
VaR imgurl = chrome. extension. geturl ("images/myimage.png ");
Document. getelementbyid ("someimage"). src = imgurl;

Cross-origin XMLHttpRequest cross-site asynchronous call, used to access APIs of other websites using plug-ins
It can be divided into local and external data

Data in the local plug-in: no permission needs to be set
VaR xhr = new XMLHttpRequest ();
Xhr. onreadystatechange = handlestatechange; // implemented elsewhere.
Xhr. Open ("get", chrome. extension. geturl ('/config_resources/config. json'), true );
Xhr. Send ();
Note: 0 indicates that the local request is successful.

For external websites, you need to set the permissions in the manifest file to add the corresponding website address, and use more internal functions of the plug-in.
"Permissions ":[
"Http://www.google.com /"
],
You can also use fuzzy match for matching URLs.
"Http: // * .google.com /"
"Http: // */" indicates that all websites are allowed to be accessed. Note that HTTPS must be compiled independently.
Built-in JSON conversion JSON. parse (...); can be used to convert a specified string to a required JS object.

Prompt again, if you want to access other websites, be sure to add permission Permissions

Message Passing

Simple one-time requests: sends a simple JSON data from a content scriptto the plug-in's background.html file, and vice versa.
Chrome. extension. sendrequest () or chrome. Tabs. sendrequest () Methods
An optional callback function that can be used to receive returned content.
For example, defined in the content script file
Chrome. extension. sendrequest ({greeting: "Hello"}, function (response ){
Console. Log (response. Farewell );
});
Some special features are used in background sending. You need to use getselected to obtain the Selected tab and then send the request.
Chrome. Tabs. getselected (null, function (Tab ){
Chrome. Tabs. sendrequest (Tab. ID, {greeting: "Hello"}, function (response ){
Console. Log (response. Farewell );
});
});

The received code is:
Chrome. extension. onrequest. addlistener (
Function (request, sender, sendresponse ){
Console. Log (sender. Tab?
"From a content Script:" + sender. Tab. url:
"From the extension ");
If (request. Greeting = "hello ")
Sendresponse ({farewell: "goodbye "});
Else
Sendresponse ({}); // snub them.
});

Long-lived connections long-period connection
Able to maintain connections and continuously send and receive data
Code for connecting content script to background (plug-in)
VaR Port = chrome. extension. Connect ({name: "knockknock "});
Port. postmessage ({joke: "Knock knock "});
Port. onmessage. addlistener (function (MSG ){
If (msg. Question = "Who's there? ")
Port. postmessage ({answer: "Madame "});
Else if (msg. Question = "Madame who? ")
Port. postmessage ({answer: "Madame... Bovary ");
});

If you want to initiate a connection from the background plug-in, you need to modify it to obtain the specified ID.
Chrome. Tabs. Connect (Tabid, {name: "knockknock "}).
Set listener connection listener
Chrome. extension. onconnect. addlistener (function (port ){
Console. Assert (port. Name = "knockknock ");
Port. onmessage. addlistener (function (MSG ){
If (msg. Joke = "Knock knock ")
Port. postmessage ({question: "Who's there? "});
Else if (msg. Answer = "Madame ")
Port. postmessage ({question: "Madame who? "});
Else if (msg. Answer = "Madame... Bovary ")
Port. postmessage ({question: "I don't get it ."});
});
});

Corresponding listening disconnection method port. Disconnect (), and corresponding event port. ondisconnect

Cross-extension messaging
Chrome. extension. onrequestexternal or chrome. extension. onconnectexternal
The method details are consistent with the above Connection events.

The Cross-Site JS attack is mentioned here. We recommend that you use the special JSON. parse method instead of the string returned by eval conversion.

The npapi plugins is used to provide JS calls to Local Binary Code. It is recommended to be used at the end. It may be very powerful.

The autoupdating and packaging sections are skipped.

Because Chrome is developed from WebKit, it can call its unique API
The V8 JS engine also provides Chrome with JSON objects.
You can integrate the required JS plug-ins, such as jquery.

Now it's over. If you have time, study again... start gwt2.0

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.