繁体   English   中英

将主机解析为IP地址,并使用Chrome扩展程序将其显示在弹出窗口中

[英]Resolve host to IP address and display it in a popup using a Chrome extension

我正在开发Chrome扩展程序以执行以下操作。

单击该图标时,弹出窗口将显示当前显示页面的IP地址。

该扩展名应该在每个页面上都有效。 但是问题是,当加载URL时,应该已经加载了当前URL的IP。 不会在显示弹出窗口时显示,以便在弹出窗口和通过Web服务获取IP地址之间没有延迟。

因此,实质上,每个选项卡的扩展弹出窗口都不同。

这应该是页面操作还是浏览器操作?

以及如何在后台从Web服务中获取数据并在实际显示之前将其分配给弹出窗口?

任何信息都非常实用。

此答案包含测试扩展的完整代码。 要进行测试,请创建每个文件,将其存储在同一目录中,然后通过chrome://extensions/ (开发人员模式)加载该文件。


“此扩展程序应适用于每个页面。” -> 浏览器动作

有两种方法可以尽快捕获页面的URL。 这两种方法都必须在后台页面中使用。

  1. 使用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 } }); 
  2. 使用chrome.webRequest API:

     chrome.webRequest.onBeforeRequest.addListener(function(details) { processUrl(details.tabId, details.url); // Defined below }, { urls: ["*://*/*"], types: ["main_frame"] }); 

两种方法都将捕获选项卡和URL。 在您的情况下- 在当前选项卡的弹出窗口中显示IP-,首选第一种方法,因为它在每次选项卡更新时都会触发。 后者只会针对http:https: URL触发。

这两种方法都将调用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"
    }
}

相关文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM