开发者

How to pass a value from to a page in Chrome extension development?

I have a popup, call 'w开发者_如何学编程elcome.html', the thing I would like to do is when the user select a text, and click my plugin, it will use some of the page information, and print back to the welcome.html. For example, the web site title, and the text which the user selected and the url. But how can I pass value to that welcome.html? Thank you.


I do a lot of this in my extension as it mines a lot of data enabling the user to easily copy it to their clipboard.

Since you're looking for a lot less data it's even simpler. When your popup is being loaded you can call the following function to retrieve the information you require;

function getData(callback) {
    chrome.tabs.getSelected(null, function (tab) {
        var data = {
            selection: '',
            title: tab.title,
            url: tab.url
        };
        /*
         * We can't call content scripts on some pages and the process will get
         * stuck if we try.
         */
        if (tab.url.indexOf('chrome') === 0 ||
                tab.url.indexOf('https://chrome.google.com/webstore') === 0) {
            callback(data);
        } else {
            chrome.tabs.sendRequest(tab.id, {}, function (response) {
                data.selection = response.selection;
                callback(data);
            });
        }
    });
}

Ensure you pass in a callback function which will be called once all the data has been extracted;

getData(function (data) {
    console.log('Title: ' + data.title);
    console.log('URL: ' + data.url);
    console.log('Selected Text: ' + data.selection);
    // Display the data instead
});

As you may have noticed the getData function sends a request to the selected tab. A content script will need to be injected in to the page in order for this to work so be sure you've configured your manifest correctly or injected it programmatically prior to calling getData or it won't work. The script that will need to be injected should resemble the following;

(function () {
    chrome.extension.onRequest.addListener(function (request, sender,
            sendResponse) {
        sendResponse({
            selection: window.getSelection().toString()
        });
    });
})();

This simply returns the currently selected text. One concern is that this data look-up could potentially cause a slight pause while the popup is rendered but you should test this yourself and experiment with it but there are solutions.

This should cover all you need to know so good luck and let me know if you need any further help as I'm aware this could be slightly overwhelming if you're new to Chrome extensions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜