// Takes a url, a GET parameter name and value and returns
// the given URL but with the given parameter at the end of
// the query portion.
function urlWithParameter(url, name, value) {
// Find the fragment since the query ends where the fragment starts.
var fragmentStart = url.indexOf('#');
if (fragmentStart < 0) { fragmentStart = url.length; }
var urlBeforeFragment = url.substring(0, fragmentStart);
// If there is no query (no '?' in URL) then start the parameter with
// a '?' to create a query. Otherwise separate the parameter from
// the existing query with a '&'.
// We use encodeURIComponent which assumes UTF-8 to escapes special URL
// characters like '#', '&', '?', '%', and '='.
// It assumes UTF-8. Any replacement that does not assume UTF-8 must escape
// at least the code-points listed above.
return urlBeforeFragment + (urlBeforeFragment.indexOf('?') < 0 ? '?' : '&')
+ encodeURIComponent(name) + '=' + encodeURIComponent(value)
+ url.substring(fragmentStart);
}
can be used thus
<script>/* the function above */</script>
<a onclick="this.href = urlWithParameter('http://twitter.com/', 'status', tab.url)" href="#">...</a>
to do what you want while still respecting the link target
implied by <base target="...">
and still displaying a useful URL on hover.
Alternatively, if you only have one parameter you need to manipulate, then you can use your earlier solution thus
<a onclick="this.href = 'http://twitter.com/?status=' + encodeURIComponent(tab.url)" href="http://twitter.com/">...</a>
EDIT: To get it working with the async chrome accessors, try the following:
<script>
function redirectWithSelectedTabUrl(link) {
chrome.tabs.getSelected(null, function (tab) {
window.location.href = tab.url
? link.href + "?status=" + encodeURIComponent(tab.url)
: link.href;
};
return false;
}
</script>
<a href="http://twitter.com/" onclick="return redirectWithSelectedTabUrl(this)">...</a>
This is simple and works across a wide range of browsers, but it will ignore the target
and may not send along referrer headers.