Chrome插件中,可以跨域的地方只有background js和popup js这两个地方,popup js是右上角那个弹出页,只有弹出的时候才有效,所以定义跨域监听大概不现实
这样只能在background js,我们需要在background js中定义一个监听函数,来监听其他页面传过来的信息。根据传来的值,判断是否是API请求
下面是一个有get和post的简易解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { 	switch(request.type) { 		case 'get': 			fetch(request.url) 				.then(function(response) { return response.json() }) 				.then(function(json) { return sendResponse(json) }) 				.catch(function(error) { return sendResponse(null) }); 		break; 		case 'post': 			fetch(request.url, { 				method: 'POST', 				mode: 'cors', 				credentials: 'include', 				headers: { 					'Content-Type': 'application/x-www-form-urlencoded' 				}, 				body: JSON.stringify(request.data) 			}) 				.then(function(response) { return response.json() }) 				.then(function(json) { return sendResponse(json) }) 				.catch(function(error) { return sendResponse(null) }); 		break; 		 		case 'test': 			sendResponse({'msg': 'test'}); 		break; 	} });
   | 
在其他页面你只需要这样调用
1 2 3 4 5 6 7 8 9
   | chrome.runtime.sendMessage( { 	 	type: 'get', 	url: 'https://api.xxxx.com/api?a=1&b=2'  }, json => { 	console.log(json); });
   | 
进一步学习:官方文档