我有一个简单的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" });
}
});
型
你知道是什么问题吗?
1条答案
按热度按时间hsgswve41#
抱歉,无法重现浏览器中的错误。
我稍微更新了一下代码。可能对你有帮助。
x
的数据