Chrome插件请求数据时请求报错(blocked:mixed-content)
- 问题原因
- 解决方案
- 方案1:配置https
- 方案1:使用background.js请求http
问题原因
问题原因是我在csdn上搜索到的,主要原因为https页面去发送http请求报错(浏览器阻止https发送http请求)
解决方案
方案1:配置https
将请求的服务器添加openssl扩展,使服务器支持https。该方法局限于服务器为自己的服务器,可以进行配置的情况下。
方案1:使用background.js请求http
1、如果你请求数据的代码位于content_scripts中,可以直接通过chrome.runtime.sendMessage来和background.js进行通信,把请求任务交给background.js即可解决。
2、如果你请求数据的代码是注入到网站中的inject_scripts,我们要先让inject_scripts和content_scripts进行通信,把网址和参数传给content_scripts,然后content_scripts再通过上面的方法把参数传给backgroud.js从而达到目的。
代码如下:
//background.js
function getPostResult(url,params,sendResponse){
$.post(url, params, function (result) {
sendResponse(result);
});
}
// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
getPostResult(request.url,request.params,sendResponse);
return true;//注意此处,异步的话返回值必须为true
});
//content_scripts
window.addEventListener("message", function(e)
{
if(e.data.type=="req_bg")
{
//向background发送数据
chrome.runtime.sendMessage({"url":e.data.url,"params":e.data.params}, function(response) {
//发送给inject
window.postMessage({"type":'bg_res',"response":response}, '*') ;
});
}
}, false);
//inject.js
//发送请求参数给content_scripts
window.postMessage({"type":"req_bg","url":url,"params":params}, '*');//type:req_bg 请求background.js bg_res background.js返回值
//接收background.js请求的数据
window.addEventListener("message", function (e) {
if (e.data.type == "bg_res") //如果是来自background的返回值
{
var result = e.data.response;
//接下来处理返回结果result
}
}, false);
以上就是我的总结,希望对同样错误的同学有帮助,有疑问可以给我留言。
觉得有帮助的同学有能力可以打赏一点C币
更多推荐
Chrome插件请求数据时 请求报错(blocked:mixed-content)
发布评论