gpt4 book ai didi

javascript - chrome扩展中的跨域ajax调用

转载 作者:行者123 更新时间:2023-12-03 07:33:10 25 4
gpt4 key购买 nike

我正在制作一个小扩展来测试我的 API。但是在进行 ajax 调用时会出现错误。

 Refused to load the script 'http://localhost:8080/acton-demouser/user1?callback=jQuery2210009971836116164923_1456851818933&format=json&_=1456851818934' because it violates the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

而我的 ajax 调用 url 是: http://localhost:8080/acton-demouser/user1

manifest.json:

{
"name": "Ajax Helper",
"version": "1.0",
"description": "My first Chrome extension.",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html",
"default_popup": "popup.html"
},
"app": {
"background": {
"scripts": ["background.js"]
}
},
"icons": { "16": "icon.png", "128": "icon.png" },
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
"permissions": [
"http://*/*"
]
}

js 文件:-

$("form").submit(function(){
var ajaxType = $('#request-method-selector option:selected').val();
var urlPrefix = 'http://localhost:8080/acton-demo';
var url = $('#url').val();
if(ajaxType === 'GET'){
$.ajax({
url: (urlPrefix+url),
error: function() {
$('#error').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
$("#success").html(data);
},
type: 'GET'
});
}

});

我在这里缺少什么。

最佳答案

您需要指定“http://localhost:8080” ' 添加到 content_security_policy 定义中作为白名单。因为您在使用 $.ajax 调用端点时使用“jsonp”作为数据类型。也就是说,它不是Ajax调用,而是脚本标签创建。因此,您必须将该域添加到 content_security_policy 定义中。

"content_security_policy": "script-src 'self' http://localhost:8080 https://ajax.googleapis.com; object-src 'self'",

基本上,我们可以指定仅具有“https”前缀的 URL。然而,为了方便开发,它允许我们指定两个域' http://localhost '和'http://127.0.0.1 '。 document 中对此进行了描述。 .

关于javascript - chrome扩展中的跨域ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35729021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com