Chrome Flask应用程序中的CORS错误,仅可从浏览器重现

yqlxgs2m  于 2023-07-31  发布在  Go
关注(0)|答案(1)|浏览(99)

我有一个简单的Flask端点和一个试图调用它的Chrome扩展。但是,我得到一个与同源策略相关的错误。当我使用cURL时,我没有看到错误。
以下是一些文件:
app.py

import logging
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

logging.getLogger('flask_cors').level = logging.DEBUG

@app.route('/headers', methods=['GET', 'POST'])
def headers():
    return dict(request.headers)

@app.route('/process_url', methods=['OPTIONS'])
def handle_preflight():
    print('preflight')
    response = app.make_default_options_response()
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    return response

@app.route('/process_url', methods=['POST'])
def process_url():
    print("processing")
    print(request.headers)
    url = request.form.get('url')
    # Process the URL here
    # You can perform any operations on the URL, such as scraping or extracting information
    return dict(request.headers)
    # Return the processed result
    #return f"The URL '{url}' has been processed."

if __name__ == '__main__':
    app.run()

字符串
manifest.json

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0",
  "description": "Description of my extension",
  "permissions": [
    "activeTab",
    "http://localhost:5000/*",
    "contextMenus"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}


content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === "sendRequest") {
      console.log('here')
      var currentUrl = window.location.href;
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "http://localhost:5000/process_url", true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          sendResponse(xhr.responseText);
        }
      };
      xhr.send("url=" + encodeURIComponent(currentUrl));
      return true;
    }
  });


background.js

chrome.contextMenus.create({
    title: "Send Request",
    contexts: ["page"],
    onclick: function(info, tab) {
      chrome.tabs.sendMessage(tab.id, { action: "sendRequest" });
    }
  });


你知道是什么问题吗?

hsgswve4

hsgswve41#

抱歉,无法重现浏览器中的错误。
我稍微更新了一下代码。可能对你有帮助。

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.post('/process-url')
def process_url():
    url = request.form.get('url')
    # ...
    return dict(request.headers)

x

{
    "manifest_version": 3,
    "name": "My Extension",
    "description": "Description of my extension",
    "version": "1.0",
    "background":{
        "service_worker":"background.js"
    },
    "content_scripts": [{
        "matches":["*://*/*"],
        "js": ["content.js"]
    }],
    "permissions":[
        "activeTab", 
        "contextMenus"
    ], 
    "host_permissions": [
        "*://*/*"
    ]
}
/** 
 * content.js 
 */
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'sendRequest') {
    const formData = new FormData();
    formData.append('url', request.url);

    fetch('http://localhost:5000/process-url', {
      method: 'POST', 
      body: formData
    }).then(response => response.ok && response.json())
      .then(sendResponse);
  }
  return true;
});
/** 
 * background.js 
 */
chrome.contextMenus.onClicked.addListener(async () => {
  const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
  if (tab) {
    const response = await chrome.tabs.sendMessage(tab.id, { action: 'sendRequest', url: tab.url });
    console.log(response);
  }
});

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
      title: 'Send Request',
      id: 'send_request', 
      contexts: ['page'],
  });
});

的数据

相关问题