Divyanshu
Divyanshu

Reputation: 363

How to redirect user to new link on clicking in chrome via extensions?

I am trying to make a chrome extension which redirects the user to modified link when user clicks the extension button.
I created manifest.json,icon file,popup.html and popup.js
But my code is not working.

I have read the answer to a similar question but still I'm not able to resolve the problem. Link--> How to modify current url location in chrome via extensions

Pseducode of what I am trying to do:
1.get url of current tab(suppose www[dot]xyz.com)
2.Modify the url (abcxyz[dot]com)
3.update the link and redirect to new link (go to abcxyz[dot]com)

This is what I've written so far....

// To get the url

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
    var targ=tabs[0].url;

});


var toBeOmitted="xyz";
    var toBeAddded="abc";
    var newTarg=targ.replace(toBeOmitted,toBeAddded);

//to update to new url
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tab) {
      chrome.tabs.update(tab.id, {url:newTarg});
});

I am not able to debug it.

Upvotes: 2

Views: 1662

Answers (2)

Divyanshu
Divyanshu

Reputation: 363

Problem in declaring variables.
Final code will look like this-->

//Declaring variables
var targ,newTarg;

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
    targ=tabs[0].url;
//defining variables here
    var toBeOmitted="xyz";
    var toBeAddded="abc";
//define newTarg without var(to make it global) or just declare outside
//and define here
    newTarg=targ.replace(toBeOmitted,toBeAddded);   
    return newTarg;
});





  chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
      chrome.tabs.update({url:newTarg});
});

Upvotes: 2

AnnoyingDog87
AnnoyingDog87

Reputation: 26

You forgot to close the function chrome.tabs.query

If it still not working, try to replace tab.id with null, that way you also don't need to use chrome.tabs.query

Example:

chrome.tabs.update(null, {url:newTarg});

Upvotes: 0

Related Questions