javascript - Resolve host to IP address and display it in a popup using a Chrome extension - Stack Overflow

I'm developing a Chrome extension to do the following.When clicked on the icon, the popup shows th

I'm developing a Chrome extension to do the following.

When clicked on the icon, the popup shows the ip address of the currently displayed page.

This extension should work on every page. But the issue is the IP of the current url should have be loaded when the url is loaded. Not when the popup is shown so that there will be no delay between the pop up and getting the IP address via a web service.

So in essence the popup of the extension is different for every tab.

Should this be a page action or a browser action ?

And how do I get the data from the web service in the background and assign it to a popup before it is actually displayed ?

Any info is really appriciated.

I'm developing a Chrome extension to do the following.

When clicked on the icon, the popup shows the ip address of the currently displayed page.

This extension should work on every page. But the issue is the IP of the current url should have be loaded when the url is loaded. Not when the popup is shown so that there will be no delay between the pop up and getting the IP address via a web service.

So in essence the popup of the extension is different for every tab.

Should this be a page action or a browser action ?

And how do I get the data from the web service in the background and assign it to a popup before it is actually displayed ?

Any info is really appriciated.

Share Improve this question edited Jul 14, 2012 at 21:44 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Jul 14, 2012 at 15:20 AmilaAmila 2,8191 gold badge28 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

This answer contains the full code for testing the extension. To test, create each file, store it in the same directory, and load it via chrome://extensions/ (developer mode).


"This extension should work on every page." -> Browser action.

There are two methods to capture the URL of a page as soon as possible. Both methods have to be used in the background page.

  1. Using 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. Using the chrome.webRequest API:

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

Either method will capture the tab and url. In your case -showing the IP in a popup for the current tab-, the first method is preferred, because it is triggered for each tab update. The latter will only be triggered for http: and https: URLs.

Either method calls the processUrl function. This function is going to process the URLs for the given tabs. I remend to cache the IP addresses, to avoid too many requests to the web service.

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);
            }
        }
    });
});

Once the IP is found, the IP is saved in a hash. This hash looks like:

hostToIP = {
    'stackoverflow.': '64.34.119.12',
    'superuser.': '64.34.119.12'
};

As you can see, two hosts may refer to the same IP. The reverse is also true: A host may have multiple IP addresses (Lookup Google, for example). The background page municates with a browser action popup, if opened.

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"
    }
}

Relevant documentation

  • Browser Actions
  • chrome.tabs API (heavily used)
  • DNS in client-side JavaScript - documentation of the web service
  • chrome.windows.getAll method (to get initial information).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745656674a4638582.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信