After Google updated version 73 these days, someone reminded me of the error of the Google Translate plug-in I wrote before. After checking the red reminder of cORS in cross-domain, I tried to solve it for many times and finally solved it. This article only describes the process with my solutions and some attempts.

Google plugins write portals

First of all, introduced the Google plug-in most of the time, are some of the expansion of Google browser function, even directly rely on itself to realize some desktop client applications, such as common have a calendar, a page refresh, email, etc., powerful have remote desktop control, etc., of science when we surf the Internet, you can look for, a bit of a crap

Develop a document address portal

Cross-domain problem

Google Plugin is a sandbox system.

The previous mechanism of the plug-in is shown as follows:

In the previous version, cross-domain can be solved through the official configuration, request data in the content, and operate the DOM of the browser page. The configuration is as follows, which may be the configuration of most developers before, and also refer to a lot of information, everyone gives the solution, but I failed this time, because it has been configured before.

Access to fetch at ‘another-site.com/’ from origin ‘example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The measures

The brute force solution, this method is to kill pigs, directly turn off the browser security mechanism

Versions after Chrome49: Windows:1.Close all Chrome browsers.2.Create a New Chrome shortcut, right-click Properties, select Target from shortcut TAB, and add --args -- disable-web-Security --user-data-dir3.Open Chrome on MAC via shortcut: Open terminal and make sure Chrome is fully exited. open -a /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dirCopy the code

The browser will then prompt you

Then I thought of the JSONP solution, because the resource I needed was to provide the JSONP request mode, so I confidently changed the request mode to JSONP, simulation code is as follows:

<! --start.js-->function jsonpFunc(jsonpParams){
    console.log(jsonpParams)
}
$.ajax({
    url: 'http://example.com'.data: 
    {
        apiKey:apikey,
        sign:sign,
        to:'zh'.query:'Hello world'
    },
    dataType: "jsonp".jsonp:'jsonpParams'.jsonpCallback:'jsonpFunc'.//jsonpCallback:jsonpFunc, // Uncaught ReferenceError: jQuery17105683612572029233_1323808231542 is not defined
    success: function(msg){
        newNode.src = msg.data;
    },
    error: function(msg){
        console.log(msg.data); }})Copy the code

In the current file, the function I defined is not considered by the other party at all. I have tried to define it in background-js and mount it under window, but due to sandbox rules, none of these functions work. If I call the function directly without quotes, the browser console will error with the comment above and click on location to see the message returned by the interface, but unfortunately I can’t retrieve it and process it.

In the solution process to find a good post [dry goods] Chrome plugin (extension) development overview, in these two pictures I found the idea

In this case, I can’t write several queues individually, I can only write a group of queues that communicate with each other, and then split the queue

<! --background.js does not work on browser pages, cross-domain -->// Listen on the function API to get the content passed from content_script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    var query = ' ',_promise=null;
    if(request.currentRequstName == 'yandex'){
        query = request.subtitle;
        var apiKey = request.apiKey;
        var to = request.configInfo.aimLang == 'undefined' ? 'zh' : request.configInfo.aimLang;
        if (query == ' ') return

        _promise = ajaxThen("https://translate.yandex.net/api/v1.5/tr.json/translate", {
            key: apiKey,
            text: query,
            lang: to
        })
    }else if(request.currentRequstName == "baidu") {// Categorize requests
        // ...
    }else if(request.currentRequstName == "youdao") {// ...}});function ajaxThen(url, params) { // Request encapsulation
    var dtd = $.Deferred();
    $.ajax({
        url: url,
        type: 'post'.data: params,
        dataType: 'json'
    }).then(function (data) {
        dtd.resolve(data);
    }, function () {
        toastr.error("submit failure"."oprate failure");
        dtd.reject();
    });
    returndtd.promise(); } <! --start.js works on browser pages, not across domains -->// Send data to background to fetch the requested data
    chrome.runtime.sendMessage({
        currentRequstName: 'youdao'.// "baidu","yandex"
        apiKey: apiKey,
        subtitle: query,
        configInfo: configInfo,
        sign: sign,
        from: from.salt: salt
    }, function (response) {
        // when background get info
    });


// Receive the data from background.js, and then do the operation
var beforeGet = null;
// Get the data passed to the backgroud
chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        if(beforeGet ! = request) {// Avoid duplicate operations
            beforeGet = request; 
            console.log("%c%s"."color: red; background: yellow; font-size: 24px;".JSON.stringify(request[0]));
            // Select operation mode according to different request mode
            if (request[2] = ='yandex') {
                yandexSendOkThenChangeSubtitle(request)
            } else if (request[2] = ="baidu") {
                baiduSendThenChangeSubtitle(request)
            } else if (request[2] = ="youdao") {
                youdaoSendThenChangeSubtitle(request)
            }
        }
    }
);
Copy the code

The above is the core implementation, the previous logic reuse can be.

The final

This project has lasted for more than eight months. I have experienced the pain and joy of this project. I hope it can really help some friends.

See Ya

References and posts

chrome developer

Chrome plug-in (extension) development overview

StackOverflow: chrome extension jsonp

MDN fetch

History article portal

👨🏫 Image compression Canvas

Vue embedded iframe. How does iframe call intra-VUE routing across domains

Remember vUE below suspension fit top implementation

Oneplus 5T, Android P downgraded

Write a Google plugin to translate Udemy+NetFlix subtitles (related)