javascript - Chrome Extension webRequest.onBeforeRequest Cancel Page -


i attempting create chrome extension queries external source reference block or allow through particular page. following part of code. new javascript, , scope seems screws me up.

chrome.webrequest.onbeforerequest.addlistener(     function(details) {          var http = new xmlhttprequest();         var url = "http://xxx.xx.xxxx";         var params = "urlcheck="+encodestring_(details.url);         http.open("post", url, true);         //send proper header information along request         http.setrequestheader("content-type", "application/x-www-form-urlencoded");          http.onreadystatechange = function() {             if(http.readystate == 4 && http.status == 200) {                 guilt = 0;                 console.log(guilt);             }else if(http.readystate == 4 && http.status == 404){                 guilt = 1;                 console.log(guilt);             }         }         http.send(params);      if(guilt == 1){         return {cancel: true};         }else{         return {cancel: false};         }      },     {urls: ["<all_urls>"],      types:["main_frame"]     },     ["blocking"]     ); 

any appreciated! thanks.

you can't that.

your code not work expected because xhr asynchronous; onreadystatechange executed after whole outer function finishes. guilt undefined or, worse, stale (from last request).

for more information, see canonical question: why variable unaltered after modify inside of function?

however, if try fix this, you'll notice can't return response within async handler.

this intentional: there no function pass , call later (like sendresponse in messaging api), because chrome will not wait you. expected respond blocking call in deterministic , fast way.

if optional opt_extrainfospec array contains string 'blocking' (only allowed specific events), callback function handled synchronously. means request blocked until callback function returns.

you could try bypass using synchronous xhr calls. not idea in general, since loading remote response takes long time, , synchronous xhr considered deprecated. though limited queries "main_frame" requests, still adds uncertain delay each load.

a proper way load set of rules server , update periodically, , when request occurs validate against local copy of rules. approach extensions adblock use.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -