Chrome扩展,使用localStorage保存ip,tabid,serverfingerprint每个标签
问题描述:
我应该提到前面我是新来的代码/ *所以我道歉,如果这个问题没有道理。我无法忍受,我试图建立一个保存IP地址,URL和服务器指纹的Chrome扩展。 serverfingerprint是一个位于响应头中的字段。使用我的background.js和localStorage,我可以保存这些信息,然后将其显示在我的弹出窗口中。这是所有罚款和丹迪,除了我不知道如何将它保存在每个选项卡的基础上,又名...如果我有5个选项卡打开,我想点击我的扩展,并显示每个网址相应的标签。例如:点击tab4并显示tab4的网址,然后点击tab2并显示tab2的网址。Chrome扩展,使用localStorage保存ip,tabid,serverfingerprint每个标签
下面的代码工作除了它不绑定到tabId,所以它不完全理想。任何想从哪里开始研究将非常感激!
我所迄今所做: background.js:
chrome.experimental.webRequest.onCompleted.addListener(function (details)
{
var headers = details.responseHeaders;
localStorage['ip'] = details.ip;
localStorage['url'] = details.url;
for (var i = 0, length = headers.length; i < length; i++)
{
var header = headers[i];
if (header.name == 'X-Server-Fingerprint')
{
localStorage['XServerFingerprint'] = header.value.toString();
break;
}
}
},{'urls': ['http://www.someurl.com/*']},['responseHeaders']);
popup.js:
document.getElementById('url').innerText = localStorage['url'];
document.getElementById('ip').innerText = localStorage['ip'];
document.getElementById('XServerFingerPrint').innerText = localStorage['XServerFingerPrint'];
答
由于每个标签都有唯一的ID(直到重新启动浏览器),你可以使用它来识别标签。
您可能只对当前选项卡感兴趣,这会让事情变得更简单,因为您不需要localStorage
(这会在浏览器重新启动之间保留数据)。只要使用背景页面的命名空间来存储数据有关的所有标签:
//background
var tabs = {}; //all tab data
chrome.experimental.webRequest.onCompleted.addListener(function (details)
{
var tabInfo = {};
tabInfo["ip"] = ...;
tabInfo["url"] = ...;
tabInfo["XServerFingerprint"] = ...;
tabs[details.tabId] = tabInfo;
}
//popup
chrome.tabs.getSelected(null, function(tab){
var tabInfo = chrome.extension.getBackgroundPage().tabs[tab.id]; //get from bg page
document.getElementById('url').innerText = tabInfo['url'];
document.getElementById('ip').innerText = tabInfo['ip'];
document.getElementById('XServerFingerPrint').innerText = tabInfo['XServerFingerPrint'];
});
如果你确实需要的localStorage那么你可以tabs
对象转换为JSON字符串,并将其存储在那里。
答
好的,所以我已经整理了我的问题!那么关于铬扩展的哈哈,这看起来几乎与塞尔格所说的一样(thx Serg !!)我写了一些不同的tho。
background.htm
chrome.experimental.webRequest.onCompleted.addListener(function (details)
{
var headers = details.responseHeaders;
var tabId = details.tabId;
var ip = details.ip;
var url = details.url;
for (var i = 0, length = headers.length; i < length; i++) {
var header = headers[i];
//custom field in response headers from my site
if (header.name == 'X-Server-Fingerprint') {
var XServerFingerprint = header.value.toString();
var data = {
ip: ip,
url: url,
fingerprint: XServerFingerprint
}
//store it
localStorage[tabId] = JSON.stringify(data);
break;
}
}
},{'urls': ['http://www.corbisimages.com/*']},['responseHeaders']);
}
and then on my popup.js
chrome.tabs.getSelected(null, function(tab) {
var parseData = JSON.parse(localStorage[tab.id]);
document.getElementById('XServerFingerprint').innerText = parseData.fingerprint;
document.getElementById('url').innerText = parseData.url;
document.getElementById('ip').innerText = parseData.ip;
});