I'm trying to use a content script to inject my own JS files into a page. The way I'm trying to do this is based on the system used by a Chrome extension called dotjs, which runs a little server on your machine, and makes AJAX reuests to localhost in order to retrieve the files from that server.
I'm fairly certain those AJAX requests will only go through if they're sent from background.js rather than a content script, due to the Same Origin Policy. I also need to use webRequest, which again only works in a background page. But, since I need to inject the stuff into the page itself, I need a content script. So my extension works with a content script that sends messages to a background page, requesting that it do all the webRequest and AJAX that it needs.
The problem is, the messages don't seem to be getting received by background.js. I have some console.log()s in the onRequest handler in background.js as you can see, and they're not showing up in my console.
manifest.json
{
"name": "dotjs",
"version": "1.5",
"description": "~/.js",
"icons": { "48": "icon48.png",
"128": "icon128.png" },
"content_scripts": [{
"all_frames": true,
"run_at": "document_start",
"matches": ["[censored]"],
"js": ["dotjs.js"]
}],
"background": {
"scripts": ["jquery.js", "background.js"]
},
"permissions": ["tabs", "webRequest", "extension"]
}
dotjs.js
console.log("dotjs.js running");
var requestFilter =
{
url: "[censored]"
};
var blockingResponse =
{
redirectUrl: "http://localhost:2262/Pigman/ips.chat.js"
};
function requestInterceptor(details)
{
return blockingResponse;
}
chrome.extension.sendRequest(
{
type: "setListener",
func: requestInterceptor,
filter: requestFilter
}
);
chrome.extension.sendRequest(
{
type: "loadJS",
filename: "Elizabot/elizabot.js"
},
function (response) { eval(response); }
);
chrome.extension.sendRequest(
{
type: "loadJS",
filename: "Elizabot/elizadata.js"
},
function (response) { eval(response); }
);
background.js
function loadJSFile(filename)
{
$.ajax({
url: 'http://localhost:2262/Pigman/' + filename + '.js',
dataType: 'text',
success: function(d){
return d;
},
error: function(){
console.log('no file found at localhost:2262/' + filename + '.js')
}
});
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse)
{
console.log("background.js received request:");
console.log(request);
if (request.type == "setListener")
{
chrome.webRequest.onBeforeRequest.addListener(request.func, request.filter);
}
if (request.type == "loadJS")
{
sendResponse(loadJSFile(request.filename));
}
}
);