Chrome Extension: Get Parameter from URL [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-08 08:15:33

问题


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?


回答1:


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"



回答2:


Not exactly a regex, but this should work:

var queryString=url.match(/\?.+$)[0].split('#')[0]

This should work in most cases. I'll try to dig up the regex I had written for this some time ago.




回答3:


Created simple function to get URL parameter in Javascript from a URL like this

.....58e/web/viewer.html?page=17&getinfo=33

    function buildLinkb(param) {
        var val = document.URL;
        var url = val.substr(val.indexOf(param))  
        var n=parseInt(url.replace(param+"=",""));
        alert(n+1); 
    }
    buildLinkb("page");

OUTPUT : 18



来源:https://stackoverflow.com/questions/11773190/chrome-extension-get-parameter-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!