Chrome plug-in popup and cross-origin requests
Tkorays <[email protected]>
Popup and other JS scripts
There are several types of JS files in chrome plug-in development: JS files in the popup window, background scripts, and content scripts.
- Popup refers to the pop-up window, which is defined by HTML and so on. This page contains scripts, mainly used for the popup interface logic, but it can also call some chrome APIs, such as communication with background.
- Background is used to process Background functions, such as processing some computing and analysis pages.
- Content is embedded into an opened page. It can be used to modify the style function of the browser page and obtain the DOM of the page.
The three of them can communicate with each other. Chrome provides some communication methods: chrome. extension. * chrome. runtime .*
Cross-origin request
Due to security issues, chrome prohibits cross-origin requests. In some scenarios, we need to send cross-origin requests in the popup script, but in chrome, the returned status is always 0. This is inconvenient. However, in the plug-in, the background script can execute cross-origin requests. Requests can also be made in the content script, but you must first set the permissions in manifest. JSON to enable cross-origin requests for some addresses.
Here are some solutions.
1. Communication
Popup sends a message, and the background executes the cross-origin request to return information. However, there is a problem here. The callback function is not executed when a message is sent in the popup (content and background communication are normal ). However, you must perform some operations after receiving the message. Therefore, this is a big problem.
2. Call the background Function
In fact, there is also the simplest method, that is, directly calling the background function. Because in popup, you can obtain the background:
var bgPage = chrome.extension.getBackgroundPage();
You only need to call the function bgpage. somefunc (); then you can use the background function.
For example, you can implement functions in the background:
Downloadpage (URL, callback) {var content = ""; // download the code, which can be a cross-origin request // ...... callback (content );};
Call in popup:
Bgpage. downloadpage ('HTTP: // www.baidu.com ', function (content) {// change the popup content in this callback function });
Chrome plug-in popup and cross-origin requests