0

Trying to develop a chrome extension to use safe browsing lookup api. Would like to know how to send message(url,lookup result) between popup.js and background.js.

this is popup.js

function myFunction() {
var url;
chrome.tabs.query(
                  {currentWindow: true, active: true},function(tabs){
                  url=tabs[0].url;

                  });
alert(url);
chrome.runtime.sendMessage({url: url}, function(response) {
                            document.getElementById("display").innerHTML=response.result;
                         //  alert(response.result);
                           });
}

window.addEventListener('DOMContentLoaded', myFunction);

this is background.js

 chrome.runtime.onMessage.addListener(
                                 function(request, sendResponse) {

                                 sendResponse({result: checkUrl(request.url)});
                                 });



function encode(str) {
    var s =  encodeURIComponent(str);


    s = s.replace('!','%21');
    s = s.replace('*','%2A');
    s = s.replace('(','%28');
    s = s.replace(')','%29');
    s = s.replace("'",'%27');


           return s;
}


var query = encode(url);

 var queryUrl = "https://sb-ssl.google.com/safebrowsing/api/lookup?        

client=CLIENT&key=AIzaSyDWNPq9LFwkQzwPl4D9EnCmYDgP7xVr5jY&appver=1.0&pver=3.1&url="+query;


function checkUrl(){

var xhr = new XMLHttpRequest();
xhr.open("GET", queryUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
           //document.getElementById("safeBrowsing").innerText = xhr.responseText;
}
}
xhr.send();

return xhr.responseText;

}

the manifest

{
 "manifest_version": 2,
   "name": "secBrowsing",


 "description": "secure your browsing as you want",
  "version":"1.0",
  "background": {
    "scripts": ["background.js"]

 },
"browser_action":
{

 "default_popup":"popup.html" 

 },
"permissions":["tabs" ,"background"]
 }
  • Please format your code properly. As-is it's impossible to read. – Xan Sep 23 '14 at 06:41
  • What exactly is not working? Are the messages being received at all? Have you tried printing all received messages in the handler? Are you certain the event is being fired to send messages in the first place? – anderspitman Sep 23 '14 at 06:55
  • Hint: There are two segments of your code where you don't take asynchronism into account (`chrome.tabs.query` and `xhr.onreadystatechange`) – devnull69 Sep 23 '14 at 07:41
  • Actually I myself have not idea why it doesn't work.Don't know whether it is because the url not passed to the background.js successfully or not successfully queried the safe browsing lookup server. Or maybe the return format is incorrect. Or my idea is entirely wrong. – Ruiting Qu Sep 23 '14 at 21:26

0 Answers0