此答案包含用于测试扩展的完整代码。要进行测试,请创建每个文件,将其存储在同一目录中,然后通过chrome://extensions/
(开发人员模式)加载它。
“这个扩展应该适用于每一页。” ->浏览器操作。
有两种方法可以尽快捕获页面的 URL。这两种方法都必须在后台页面中使用。
使用chrome.tabs.onUpdated
.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'loading' && changeInfo.url) {
processUrl(tabId, tab.url); // or changeInfo.url, does not matter
}
});
使用chrome.webRequest
API:
chrome.webRequest.onBeforeRequest.addListener(function(details) {
processUrl(details.tabId, details.url); // Defined below
}, {
urls: ["*://*/*"],
types: ["main_frame"]
});
任何一种方法都将捕获选项卡和 url。在您的情况下-在当前选项卡的弹出窗口中显示 IP-,首选第一种方法,因为它会在每个选项卡更新时触发。后者只会为http:
和https:
URLs 触发。
任何一种方法都会调用该processUrl
函数。此函数将处理给定选项卡的 URL。我建议缓存 IP 地址,以避免对 Web 服务的请求过多。
background.js
var tabToHost = {};
var hostToIP = {};
function processUrl(tabId, url) {
// Get the host part of the URL.
var host = /^(?:ht|f)tps?:\/\/([^/]+)/.exec(url);
// Map tabId to host
tabToHost[tabId] = host ? host=host[1] : '';
if (host && !hostToIP[host]) { // Known host, unknown IP
hostToIP[host] = 'N/A'; // Set N/A, to prevent multiple requests
// Get IP from a host-to-IP web service
var x = new XMLHttpRequest();
x.open('GET', 'http://www.fileformat.info/tool/rest/dns.json?q=' + host);
x.onload = function() {
var result = JSON.parse(x.responseText);
if (result && result.answer && result.answer.values && result.answer.values[0]) {
// Lookup successful, save address
hostToIP[host] = result.answer.values[0].address;
setPopupInfo(tabId);
}
};
x.send();
}
// Set popup info, with currently (un)known information
setPopupInfo(tabId);
}
function setPopupInfo(tabId) { // Notify all popups
chrome.extension.getViews({type:'popup'}).forEach(function(global) {
global.notify(tabId);
});
}
// Remove entry from tabToIp when the tab is closed.
chrome.tabs.onRemoved.addListener(function(tabId) {
delete tabToHost[tabId];
});
// Add entries: Using method 1 ( `onUpdated` )
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'loading' && changeInfo.url) {
processUrl(tabId, tab.url); // or changeInfo.url, does not matter
}
});
// Init: Get all windows and tabs, to fetch info for current hosts
chrome.windows.getAll({populate: true}, function(windows) {
windows.forEach(function(win) {
if (win.type == 'normal' && win.tabs) {
for (var i=0; i<win.tabs.length; i++) {
processUrl(win.tabs[i].id, win.tabs[i].url);
}
}
});
});
找到 IP 后,将 IP 保存在哈希中。这个哈希看起来像:
hostToIP = {
'stackoverflow.com': '64.34.119.12',
'superuser.com': '64.34.119.12'
};
如您所见,两台主机可能引用同一个 IP。反之亦然:一个主机可能有多个 IP 地址(例如Lookup Google)。如果打开,后台页面与浏览器操作弹出窗口进行通信。
popup.js
// Get initial tab and window ID
var tabId, windowId;
chrome.tabs.query({active:true, currentWindow:true, windowType:'normal'},
function(tabs) {
if (tabs[0]) {
// Found current tab
window.tabId = tabs[0].id;
windowId = tabs[0].windowId;
requestUpdate();
}
});
// Receive tab ID updates
chrome.tabs.onActivated.addListener(function(activeInfo) {
if (activeInfo.windowId === windowId) {
requestUpdate();
}
});
// Communication with background:
var background = chrome.extension.getBackgroundPage();
// Backgrounds calls notify()
function notify(tabId, url, ip) {
if (tabId === window.tabId) { // Tab == current active tab
requestUpdate();
}
}
// Get fresh information from background
function requestUpdate() {
// tabId is the current active tab in this window
var host = background.tabToHost[tabId] || '';
var ip = host && background.hostToIP[host] || 'N/A';
// Now, do something. For example:
document.getElementById('host').textContent = host;
document.getElementById('ip').textContent = ip;
}
popup.html
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Host to IP</title>
<script src="popup.js"></script>
</head>
<body style="white-space:pre;font-family:monospace;">
Host: <span id="host"></span>
IP : <span id="ip"></span>
</body>
</html>
manifest.json
{
"name": "Host To Tab",
"manifest_version": 2,
"version": "1.0",
"description": "Shows the IP of the current tab at the browser action popup",
"background": {"scripts":["background.js"]},
"permissions": ["http://www.fileformat.info/tool/rest/dns.json?q=*", "tabs"],
"browser_action": {
"default_popup": "popup.html"
}
}
相关文件