javascript 从 chrome.contextMenus.onClicked 侦听器中获取当前 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21078989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:59:57  来源:igfitidea点击:

Get current URL from within a chrome.contextMenus.onClicked listener

javascriptgoogle-chromegoogle-chrome-extension

提问by xKripz

I'm creating my first Chrome extension and I need some help. I I think everything is working except the fact that I can't get the current URL of the tab.

我正在创建我的第一个 Chrome 扩展程序,我需要一些帮助。我认为一切正常,除了我无法获取选项卡的当前 URL。

var menu = chrome.contextMenus.create({
    "title": "extension",
    "contexts": ["all"]
  });

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
});

chrome.contextMenus.onClicked.addListener(function(activeTab)
{

    chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
    });

    var finalUrl = "http://example.com/";

    finalUrl += encodeURI(siteUrl);

    // Open the page up.
    chrome.tabs.create(
        {
            "url" : finalUrl
        }
    );
});

Can anyone please help me? Thanks.

谁能帮帮我吗?谢谢。

EDIT:

编辑:

Thank you for your replies. I got it working by moving

谢谢您的回复。我通过移动让它工作

var finalUrl = "http://example.com/";

    finalUrl += encodeURI(siteUrl);

    // Open the page up.
    chrome.tabs.create(
        {
            "url" : finalUrl
        }

Inside

里面

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
        var siteUrl = tabs[0].url;
    });

回答by Mike M

chrome.tabs.getCurrent(function(tab){
    alert(tab.url);
});

OR if you're in a content script,

或者,如果您在内容脚本中,

alert(document.location.href);

回答by gkalpak

The info you require are provided to you already in the callback of the onClickedlistener.

您需要的信息已在onClickedlistener的回调中提供给您。

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    // The URL of the tab (if any)
    var tabURL = tab && tab.url;

    // The URL of the page (if the menu wasn't triggered in a frame)
    var pageURL = info.pageUrl;

    // The URL of the frame (if the menu was triggered in a frame)
    var frameURL = info.frameUrl;

E.g. you could achieve what you want like this:

例如,您可以像这样实现您想要的:

manifest.json:

清单.json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },

    "permissions": ["contextMenus"]
}

background.js:

背景.js:

var baseURL = 'http://example.com/';

chrome.contextMenus.create({
    id: 'myMenu',   // <-- event-pages require an ID
    title: 'Do cool stuff',
    contexts: ['all']
}, function () {
    /* It is always a good idea to look for errors */
    if (chrome.runtime.lastError) {
        alert('ERROR: ' + chrome.runtime.lastError.message);
    }
});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    /* Check which context-menu was triggered */
    if (info.menuItemId === 'myMenu') {
        /* Get the URL of the frame or (if none) the page */
        var currentURL = info.frameUrl || info.pageUrl;

        /* Open a new tab */
        chrome.tabs.create({
            url: baseURL + encodeURI(currentURL)
        });
    }
});

回答by Ahmed Gaber

If you are using content script you can use

如果您使用的是内容脚本,则可以使用

document.location.href

document.locationis Object and can provide set of useful chunks in the URL

document.location是对象,可以在 URL 中提供一组有用的块

  • document.location.hostreturns domain name ex: "http://www.google.com/"
  • document.location.pathreturns the part after the domain name
  • document.location.hashreturns whatever after # symbol in the url
  • document.location.host返回域名前:“ http://www.google.com/
  • document.location.path返回域名后的部分
  • document.location.hash返回 url 中 # 符号之后的任何内容

回答by Siddarth Kanted

Function:

功能:

function getCurrentUrl(callBackFuntion){
//you are in content scripts
    if(null == chrome.tabs || null == chrome.tabs.query){
        callBackFuntion(document.location.href);
    }else{
//you are in popup
        var queryInfo = {
            active: true, 
            currentWindow: true
        };
        chrome.tabs.query(queryInfo, function(tabs) {
            var tab = tabs[0]; 
            callBackFuntion(tab.url);
        }); 
    }
}

Function call:

函数调用:

function alertUrl(url){
    console.log("currentUrl : " + url);
}
getCurrentUrl(alertUrl);