CORS Chrome Extension with manifest version 2

前端 未结 3 1246
花落未央
花落未央 2020-12-03 10:40

Is it possible to use CORS when writing a google chrome extension?

I saw this, http://developer.chrome.com/extensions/contentSecurityPolicy.html

And I tried

相关标签:
3条回答
  • 2020-12-03 11:03

    To enable cross-origin Ajax from your extension to Twitter, you simply need to list Twitter as a host permission in your manifest:

    ...
    "permissions": [
        "*://*.twitter.com/*"
    ],
    ...
    
    0 讨论(0)
  • 2020-12-03 11:11

    Explanation

    As of Chrome 73, cross site requests are blocked. (Even if you have the hosts in your permissions property.) Some sites seem to get through unblocked but I'm sure eventually most won't.

    You have to make the request in a background page...


    Setup

    Add a section to your manifest.json to point to the background page.

    "background": {
      "scripts": ["bg_page.js"],
      "persistent": false
    }
    

    Create the background page: bg_page.js

    chrome.runtime.onMessage.addListener(
        function(url, sender, onSuccess) {
            fetch(url)
                .then(response => response.text())
                .then(responseText => onSuccess(responseText))
            
            return true;  // Will respond asynchronously.
        }
    );
    

    Then use it in main.js

    chrome.runtime.sendMessage( //goes to bg_page.js
          url,
          data => dataProcessFunction(data)
    ); 
    

    Additional Tips

    If you do anything like console.log() from the bg page, click the "inspect views background page" link in your extension's square in chrome's extensions manager and you'll get a separate dev tools window for everything that happens with your background page.

    If you want to see the docs for yourself, check out step 2 of the Recommended Developer Actions section here: https://www.chromium.org/Home/chromium-security/extension-content-script-fetches#TOC-2.-Avoid-Cross-Origin-Fetches-in-Content-Scripts

    0 讨论(0)
  • 2020-12-03 11:12

    Add the header Access-Control-Allow-Origin: * to the response of your remote server if possible. Here is a tutorial for various backend servers: add CORS support to backend server

    0 讨论(0)
提交回复
热议问题