It seems I have found myself in a catch 22.
I am using the Chrome Web Request event in an extension to get the URL of all web requests as such:
chrome.webRequest.onBeforeRequest.addListener(
function(request) {
var cat = getCategory(request.url);
if(cat == "1") {
return {redirectUrl: "http://google.com"}
} else {
return {cancel: false}
}
}
});
Then, I want to query my server using PHP to get the URL’s category. If it has a category of 1, I want to block it, if it has a category of 0, I want to allow the request to go through.
The big issue I’m seeing is that because there’s an AJAX request in the getCategory function, it doesn’t return a value and execution just continues as normal. I need to find a way to block execution until a return is actually received somehow but I’m not quite sure how to do that while still being able to return the redirect URL to the listener function.
Synchronous requests would almost work, except that you can’t set a timeout with a synchronous AJAX request. As such, if our server goes down, everyone’s web requests will be blocked regardless of category -- not ideal.
function getCategory(url) {
request = $.ajax( // params);
request.done(function)
// this code executes even before the done block finishes
}
I’ve tried using AJAX bindings like the .done() function currently being used here. I’ve also tried finding ways to make a synchronous request timeout and using .when().then() function combinations but I’m unable to find a way to return the value in the right scope from in those.
Is there a way I can get this value from the ajax request to the outer function? Everything I’ve seen to try has the wrong return scope. Does anyone know if this is somehow possible?
Ideas about restructuring the code also accepted! (As long as it will work with chrome.webRequest)