如何在我的页面操作弹出窗口中获取当前打开的选项卡的URL? [英] How to get the currently opened tab's URL in my page action popup?

查看:180
本文介绍了如何在我的页面操作弹出窗口中获取当前打开的选项卡的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自动登录到我的服务器的扩展。所以我创建了一个后台页面来检查当前的URL,如果它符合我的URL正则表达式,我将显示页面动作图标。点击页面动作后,我打开一个带有一些字段的弹出窗口。我需要获取当前打开的URL并将其填充到弹出窗口的某个字段中(例如,当我们单击标准书签页面操作时,URL会自动填充到打开的弹出窗口中)。我如何在Chrome扩展中做这样的事情?我尝试从背景页面传递消息到弹出的HTML,但它不起作用。是否有可能发送这样的消息?此外,我尝试设置弹出的HTML文件的onload,但我注意到它没有触发。请建议一个合适的方法来处理这种情况。 使用 chrome.tabs.query ,并带有以下参数:




  • queryInfo对象:

    • active:true

    • lastFocusedWindow:true - 要选择活动窗口


  • 回调函数:

    此函数接收一个参数:一组匹配的选项卡。由于只有一个窗口可以处于活动状态,并且此窗口中有一个标签,因此该数组只有一个元素。此元素是一个包含 Tab 签名< a>。



代码片段:

  chrome.tabs.query({
active:true,//选择活动标签
lastFocusedWindow:true //在当前窗口中
},function(array_of_Tabs){
//由于在一个活动窗口中只能有一个活动标签,
//数组只有一个元素
var tab = array_of_Tabs [0];
//例如:
var url = tab.url;
// ...用url变量
});

activeTab 工作。

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.

解决方案

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.

这篇关于如何在我的页面操作弹出窗口中获取当前打开的选项卡的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆