尝试开发chrome扩展以使用安全浏览查找API。想知道如何在popup.js和background.js之间发送消息(url,查找结果)。
这是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);
这是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;
}
清单
{
"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"]
}