We all know that content script of chrome extension has limitations, But it also allows to parse json data through XMLHttpRequest. I wanted to know how?
Here i've the data in json file, assume it as
links.json
{"list1":[
{"alt": "text1", "link": "img1.jpg"},
{"alt": "text2", "link": "img2.jpg"},
{"alt": "text3", "link": "img3.jpg"}
]}
Content-script file
script.js
function dip() {
var JSONFile_url = chrome.extension.getURL("links.json");
// JSONFile_url is set to "chrome-extension://[extensionID]/links.json"
var linkarr;
var JSON_req = new XMLHttpRequest();
JSON_req.overrideMimeType("application/json");
JSON_req.open('GET', JSONFile_url, true);
//JSON_req.setRequestHeader("Content-type", "application/json");
JSON_req.onreadystatechange = function()
{
if( JSON_req.readyState == 4 )
{
linkarr = JSON.parse(JSON_req.responseText);
everything goes fine until this point. But JSON.parse is not working as expected & linkarr remains with undefined value.
}
}
JSON_req.send();
//... some additional code goes here..
mm=document.createElement("div");
mm.appendChild(document.createTextNode(linkarr));
d.appendChild(mm); //appends tag in html page
//... some additional code goes here..
}
dip(); //calling main function...
manifest.json
{
"manifest_version": 2,
"name": "Simple content script extension",
"version": "3.0",
"icons": {
"256": "icon.png"
},
"permissions": ["http://*.somehost.com/*"],
"content_security_policy": "connect-src 'self'; script-src 'self'; object-src 'self'",
"content_scripts": [
{
"matches": ["http://*.somehost.com/*"],
"css": ["script.css"],
"js": ["script.js"],
"run_at": "document_end"
}
],
"converted_from_user_script": true,
"web_accessible_resources": ["links.json"]
}
Output
Undefined
Now i've 3 options here,
- debug the above code to get the array/object list from json data/file.
- use the xhr code in background javascript page.
- make a javascript file & store the json data into a variable & include it in the content_scripts under manifest.json to access that variable.
Please help me to go with the 1st option here. OR any other working method will be fine.
Note: This code is under content script of chrome extension. for more refer this https://developer.chrome.com/extensions/content_scripts https://developer.chrome.com/extensions/contentSecurityPolicy