Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - How to get the currently opened tab's URL in my page action popup?

I want to create an extension for automatically logging into my servers. So I created a background page to check the current URL and if it conforms to my URL regex, I'll display the page action icon. On click of the page action I'm opening a popup with some fields. I need to get the currently opened URL and fill it in one of the fields in the popup(like when we click the standard bookmark page action, the URL gets automatically filled in the popup that opens). How can I do something like this in chrome extensions? I tried Message Passing from the background page to the popup html but it is not working. Is it possible to send messages like that? Also I tried setting onload for the popup html file but i noticed that it is not triggering. Please suggest a suitable method to deal with this scenario.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use chrome.tabs.query with the following parameters:

  • queryInfo object:
    • active: true - To get the active tab
    • lastFocusedWindow: true - To select the active window
  • callback function:
    This function receives one argument: An array of matched tabs. Since only one window can be active, and one tab within this window, the array has only one element. This element is an object with the Tab signature.

Code snippet:

// Do NOT forget that the method is ASYNCHRONOUS
chrome.tabs.query({
    active: true,               // Select active tabs
    lastFocusedWindow: true     // In the current window
}, function(array_of_Tabs) {
    // Since there can only be one active tab in one active window, 
    //  the array has only one element
    var tab = array_of_Tabs[0];
    // Example:
    var url = tab.url;
    // ... do something with url variable
});

The activeTab permission is sufficient for this to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...