I'm just working on a 'simple' extension to add a parameter to the end of the current url. I've managed to get the current url, but can't perform a redirect to refresh the page with the added parameter. Code I have is as follows:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"persistent": false,
"scripts": ["bgscript.js"]
},
"permissions": [
"tabs"
]
}
bgscript.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var currentUrl = tabs[0].url;
chrome.extension.sendRequest({redirect: currentUrl + "?customparam=1"});
});
});
Anyone have any ideas on how to perform a redirect like this?
I'm just working on a 'simple' extension to add a parameter to the end of the current url. I've managed to get the current url, but can't perform a redirect to refresh the page with the added parameter. Code I have is as follows:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"persistent": false,
"scripts": ["bgscript.js"]
},
"permissions": [
"tabs"
]
}
bgscript.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var currentUrl = tabs[0].url;
chrome.extension.sendRequest({redirect: currentUrl + "?customparam=1"});
});
});
Anyone have any ideas on how to perform a redirect like this?
Share Improve this question asked Jan 17, 2014 at 17:39 wickywillswickywills 4,2043 gold badges40 silver badges55 bronze badges2 Answers
Reset to default 7The active tab at the time of clicking the browser-action is passed as an argument to the onClicked
listener callback.
Furthermore, as mentioned in your ment, a little care is needed to append the custom query-parameter in the proper location and prepend it with the proper symbol. Specifically, the custom parameter should be placed before the hash (if any) and after the pathname (if any), but if there are more query parameters present it should be prepended with &
instead of ?
.
var customParam = encodeURI('customparam=1');
chrome.browserAction.onClicked.addListener(function (tab) {
var url = tab.url;
var hashStart = (url.indexOf('#') === -1) ? url.length : url.indexOf('#');
var querySymbol = (url.indexOf('?') === -1) ? '?' : '&';
var newUrl = url.substring(0, hashStart) + querySymbol + customParam +
url.substring(hashStart);
chrome.tabs.update(tab.id, {url: newUrl});
});
Nevermind, got it:
bgscript.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var currentUrl = tabs[0].url;
var newUrl = currentUrl + "?customparam=1"
chrome.tabs.update({url:newUrl});
});
});