Bill: Chrome extensions develop AJAX requests

Source: Internet
Author: User

After an update, Chrome has completely banned Content_script from HTTPS to HTTP for security reasons, even if it is normally prompted in the console. This is good for the web, but it's bad for extensions. Usually it's easy to request data, and now it's not that easy. Fortunately, Chrome also provides Background_script, which uses the Content_script and Background_script communication to implement AJAX requests, skipping Chrome's limit.

Content_script

As you know from the name, Content_script is implanted and will be implanted into matching web pages. Executes after the page load is complete. The most useful place to Content_script is to manipulate the DOM on the Web page. Everything usually do the front end of some operations it can do, like what to add, modify, delete dom, get DOM value, listen to events and so on, can be easily done. So, if you want to get someone else's login account and password, is a very easy thing, only need to add content_script, listen to the account and password text box, get the value of the data sent to their own server on it. So, in particular, do not install extensions, especially extensions that are not downloaded from the official extension repository.

Using Content_script

To use Content_script, you need to configure it in Manifest.json as follows:

{    "manifest_version": 2,    "name": "My Extension",    "description": "Extension description",    "version": "1.0",    "content_scripts": {        "js": [            "Content.js"        ]    }}

In this way, after the page is loaded, the content.js is loaded and the page elements can be controlled in the content.js. If you want to use jquery in Content.js, you need to add the jquery file to Content.js, such as:

Content_script using jquery
{"    content_scripts": {        "js": [            "Jquery.js",            "Content.js"        ]    }}

In addition to loading the js,content_scripts, you can also load CSS files, which will make your extension beautiful, such as:

Content_script using CSS
{"    content_scripts": {        "js": [            "Content.js"        ],        "CSS": ["Style.css"]    }}

In Content_scripts, there is also an important setting is matches, which is used to configure, in line with the extended use of the URL, such as: I just want this extension to open www.jgb.cn only when enabled, then matches will write:

Set up a matching site
{"    content_scripts": {        "js": ["            content.js"        ],        "CSS": ["Style.css"]    },    "matches": [        "http://*.jgb.cn/*"    ]}

If you want to match www.amazon.com, then add:

{    "matches": [        "http://*.jgb.cn/*",        "http://*.amazon.com/*"    ]}

Note that HTTP is only available for HTTP, such as Amazon.com http and HTTPS, so you have to add HTTPS, as follows:

{    "matches": [        "http://*.jgb.cn/*",        "http://*.amazon.com/*",        "https://*.amazon.com/*"    ]}
Background_script

It starts when the chrome extension starts, does its thing, and waits for the instructions you give him. It has no way to control the page elements, but can tell it through Content_script. Ajax in the same way, if you want to request data from another server when the page is opened, you can tell Background_script to ask for it, and then send the returned data to Content_script. This will not be affected by the browser's security restrictions.

Using Background_script

To use Background_script, you need to configure it in Manifest.json as follows:

{    "manifest_version": 2,    "name": "My Extension",    "description": "Extension description",    "version": "1.0",    "background": {        "scripts": [            "Background.js"        ]    }}

Using jquery and content_scripts, you need to add the jquery file to the Background.js front, such as:

Using jquery in Background_script
{"    background": {        "scripts": [            "Jquery.js",            "Background.js"        ]}    }
Cross-domain

Ajax is not allowed across domains by default, but extensions provide cross-domain configuration, as mentioned in the previous basic introduction, which is permissions, which can allow the extension to use Chrome's features, but also allows JS to implement cross-domain access to the directory site, such as:

{    "Permissions": [        "http://www.jgb.cn/"//Allow cross-domain access www.jgb.cn    ]}

With the above configuration, it's time to look at how to implement AJAX requests through background_scripts.

Send a request to background

There are several ways to send a request to Background_script in Content_script, here is only one of my usual, should say, can satisfy the use of most cases, other methods, please query the document, the method is as follows:

Chrome.extension.sendMessage ({}, CallBack);

The SendMessage () method, which has two parameters, is the first data to be sent, just like a POST request, and the second is a callback function. As in Content_script, click a button to send a string to the Background_script

$ (function () {    $ ("#button"). Click (function () {        chrome.extension.sendMessage ({' txt '): ' Here is the content sent '}, function ( d) {            console.log (d);///print the return information to the console        });})    
Listening to content requests in background

Listen for content requests in background, using Chrome.extension.onMessage.addListener (), as an example:

Chrome.extension.onMessage.addListener (Function (Objrequest, _, Sendresponse) {});

Objrequest, which is the parameter of the request, in the previous example is {' txt ': ' Here is the content sent '}, you can get the content through ObjRequest.txt. is actually a dictionary.

Sendresponse, for the return value method, you can return the data to Content_script, then a simple example would be:

Chrome.extension.onMessage.addListener (Function (Objrequest, _, Sendresponse) {    var strText = objRequest.txt;    The information can be sent over Ajax to the server    $.ajax ({        URL: ' http://www.jgb.cn/',        type: ' POST ',        data: {' txt ': strText},        DataType: ' JSON ',    }). Then (function () {        //) return the correct information to Content_script        sendresponse ({' Status ': $});    } , function () {        //returns the error message to Content_script        sendresponse ({' Status ': $});})    ;

In this way, the implementation of Content_script to Background_script to send the request, and use Background_script to perform AJAX requests, very simple and useful

On this basis, the addition of some conditions and data, it can be a good implementation of receiving, sending data operation. For example, request or send data to your own server.

Enable AJAX requests to HTTP pages on HTTPS pages by modifying chrome boot parameters

In addition to using BACKGROUND_SCRIPT to initiate AJAX requests, you can do this by modifying Chrome's startup parameters. The parameters are:--allow-running-insecure-content, Operation Method:

1. Right-click Chrome shortcut, select Properties
2, at the end of the goal, input--allow-running-insecure-content, there is a space in the middle

This allows Chrome to allow you to initiate an AJAX request to HTTP on the HTTPS page. This method can achieve the goal, but is not recommended because it is unscientific.

Original: http://www.cnblogs.com/onlyfu/p/4458025.html

Bill: Chrome extensions develop AJAX requests

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.