Chrome扩展程序:从URL获取参数 [英] Chrome Extension: Get Parameter from URL

查看:1044
本文介绍了Chrome扩展程序:从URL获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

在JavaScript中获取查询字符串值


我是致力于Chrome的扩展。
我已经计算出如何从实际的Chrome标签中获取网址。

  chrome.tabs.getSelected( null,function(tab){
document.getElementById('currentLink')。innerHTML = tab.url;
});

但现在我需要知道如何从URL获取特定的参数。
我已经尝试了不同的Javascript函数,但是当我实现它们时,我的扩展停止工作。

所以:
如何获得特定参数来自实际的URL?

解决方案

要在单个正则表达式中获取查询字符串,请使用:

  var queryString = /^[^#?]*(\?[[#]+|)/.exec(tab.url)[1] ; 
//正则表达式的解释:
// ^ [^#?] *(\?[^#] + |)
//<以任何非#/?字符串><查询字符串OR nothing>

然后,使用以下函数来获取特定键的值:

  function getParameterByName(queryString,name){
//退出特殊的RegExp字符
name = name.replace(/ [[^ ^ $。|?* +(){} \\] / g,'\\ $&');
//创建正则表达式
var regex = new RegExp((?:[?&] | ^)+ name +=([^&#] *));
//尝试获得匹配
var results = regex.exec(queryString);
return decodeURIComponent(results [1] .replace(/ \ + / g,))|| ;
}

//用法:
//示例:tab.url =http://example.com/path?foo=bar&key_name=qs_value#
var queryString = /\?[^#]+(?=#|$)|$/.exec(tab.url)[0];
var value = getParameterByName(queryString,'qs_name');
//结果:value =value;

//示例2:使用该函数从当前页面的URL中获取参数。
//(例如在内容脚本中)
var value = getParameterByName(location.search,'qs_name');
//结果:value =value


Possible Duplicate:
Get query string values in JavaScript

I am working on a extension for Chrome. I already figured out how to get the URL from the actual Chrome-Tab.

chrome.tabs.getSelected(null, function(tab) {
  document.getElementById('currentLink').innerHTML = tab.url;
});

But now i need to know how to get a specific Parameter from the URL. I already tried out different Javascript-Functions but when i implement them, my Extension stops working.

So: How can i get a specific parameter from the actual URL?

解决方案

To get a query string in a single regexp, use:

var queryString = /^[^#?]*(\?[^#]+|)/.exec(tab.url)[1];
// Explanation of RegEx:
// ^[^#?]*                          (\?[^#]+   | )
// <Starts with any non-#/? string><query string OR nothing>

Then, use the following function to get the value of a specific key:

function getParameterByName(queryString, name) {
    // Escape special RegExp characters
    name = name.replace(/[[^$.|?*+(){}\\]/g, '\\$&');
    // Create Regular expression
    var regex = new RegExp("(?:[?&]|^)" + name + "=([^&#]*)");
    // Attempt to get a match
    var results = regex.exec(queryString);
    return decodeURIComponent(results[1].replace(/\+/g, " ")) || '';
}

// Usage:
// Example: tab.url = "http://example.com/path?foo=bar&key_name=qs_value#"
var queryString = /\?[^#]+(?=#|$)|$/.exec(tab.url)[0];
var value = getParameterByName(queryString, 'qs_name');
// Result : value = "value";

// Example 2: Using the function to get a parameter from the current page's URL.
//  (e.g inside content script)
var value = getParameterByName(location.search, 'qs_name');
// Result : value = "value"

这篇关于Chrome扩展程序:从URL获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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