I am trying to fetch data from an API using XHR.The request will be made when I click on the context item after selecting a some text. I have added permission of my localhost in manifest file and XHR request function in background script. But CORS policy is not allowing it for some reason. In the documentation of Chrome extension it says I must use it in background script. I tried to use it on content script too. It sends request from content script to the server but fails to retrieve data.
Can anyone help me in that case. Thanks in advance.
manifest.json
{
"name": "Towel Reviewer",
"version": "1.0",
"description": "Grabing the Header Name & Header Link",
"permissions": [
"storage","declarativeContent",
"activeTab","http://localhost/*",
"contextMenus","tabs","http://*/*",
"https://*/*", "http://localhost/*",
"http://localhost/db1/getdata.php?*"],
"background": {
"scripts": ["background.js","event.js"],
"persistent": false
},
"browser_action": {
// "default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"content_scripts":[{
"matches" : ["<all_urls>"],
"js" : ["jquery-3.4.1.min.js","content.js","popup.js"]
}],
"manifest_version": 2}
background.js
let contextMenuItem ={
"id":"TowelReviewer",
"title": "Fetch",
"contexts":["selection"]
};
function make(urls){
alert(urls)
var xhr = new XMLHttpRequest();
xhr.open("GET", urls, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
console.log(resp);
}
}
xhr.send();
}
chrome.contextMenus.create(contextMenuItem);
chrome.contextMenus.onClicked.addListener(function(clickData){
let pre = "https://amzn";
if(clickData.menuItemId == "TowelReviewer" && clickData.selectionText ){
if( (clickData.selectionText+"").startsWith(pre)){
url = "http://localhost/db1/getdata.php?link=";
url = url + clickData.selectionText;
make(url);
}
}
})
Error From background console:
Access to XMLHttpRequest at 'http://localhost/db1/getdata.php?link=https://amzn.to/2asdf' from origin 'chrome-extension://hcilieaalhffbpnnmojonlgkhmebmmcm' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.