您的位置:首页 > 其它

开发chrome插件时遇到的一些问题

2018-01-18 14:56 411 查看

开发chrome插件时遇到的一些问题

背景:在一个运行在chrome浏览器上web应用基础上开发插件,web应用的协议为https

chrome插件开发相关知识https://www.cnblogs.com/liuxianan/p/chrome-plugin-develop.html

chrome官网https://developer.chrome.com/extensions

由于需要在content_script中调用后端接口(接口协议为http),且接口域名和web应用部署的域名不一致,固需解决跨域问题。

根据以往经验,大致有以下三种方式:

后端设置Access-Control-Allow-Origin

使用jsonp调用

使用iframe

运行时报错:Mixed Content: The page at XXXX was loaded over HTTPS, but requested XXXX. This request has been blocked; the content must be served over HTTPS.

原因:http请求没有加密,容易受到MITM攻击,导致https连接被劫持,所以chrome在某个版本之后(具体哪个版本没有去查)就禁止了在https中获取http资源。

分析:以上三种方式都没有办法直接绕开http协议,最直接的就是让后台接口支持https调用就行(安全性而言也能有所提高)。还有一种方式是,在content_script 中将请求转发至 background,再在background中请求后台。

将http升级成https是肯定没有问题的,所以这里对第二种方案在进行可行性研究。

content_script中发送消息给background

chrome.extension.sendMessage({uri:"xdd_add",data:{content:content,title:title},url:"http://localhost:8080/elephant/plugin/savePub"}, function(response) {
console.info("xdd_add",response);
});


background中监听消息,并请求后端接口

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
console.log("Request comes from content script " + sender.tab.url);
dc(request,sendResponse);
//由于需要异步调用sendResponse,所以需要加上return true,通知sendResponse函数等待调用
return true;
});

/**
* dispatch controller
*/
function dc(request,sendResponse){
if (request.uri == "xdd_add") {
//这里用到jQuery,需注意不能通过远程获取js,需要将script下载到本地并打包到插件中
$.ajax({
url:request.url,
data:request.data,
success:function(result){
console.info(result);
sendResponse(result);
}
});
}
}


这里需要在manifest.json文件中的permissions设置相关url,才能进行跨域请求:

"permissions": [
"http://localhost:8080"
],


如果没有这么做的话,还是会受到同源策略的约束,从而请求失败。当然你也可以这么做:

后端设置Access-Control-Allow-Origin

//这里xxxxxxxxxxxxxxxxxxxxxxxxx 是指你的插件id
httpServletResponse.setHeader("Access-Control-Allow-Origin","chrome-extension://xxxxxxxxxxxxxxxxxxxxxxxxx");


这里之所以没有用jsonp方式,是因为CSP(Content Security Policy)。

具体文档:https://div.io/topic/1669

jsonp是同过
<script>
标签来加载资源的,它在CSP的限制范围内。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  chrome chrome插件