Magic AndWebDev
Magic AndWebDev

Reputation: 137

How do I use a custom function in background.js for a Chrome Extension?

I'm writing a Chrome extension and I want to call a function in my background.js.

This is the function:

function getUrlVars(url) {
  var vars = {};
  var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    if(vars[key]){
      if(vars[key] instanceof Array)
        vars[key].push(value);
      else
        vars[key] = [vars[key], value];
    }else
      vars[key] = value;
  });
  return vars;
}

It returns a parameter of the url. I put this function in background.js, but when I call it, it doesn't work. I call the function here:

chrome.webRequest.onBeforeRequest.addListener(function(details){ 
  chrome.tabs.get(details.tabId, function (tab) { 
    source=getUrlVars(details.url)[iapisource];
    id=getUrlVars(details.url)[iapiid];
    redirectUrl=tab.url+"?iapisource="+source+"&iapiid="+id;
  });
  return {cancel : true , redirectUrl : redirectUrl}; 
},
// block requests matching this url
{urls: ["*://*/*iapisource*iapiid*"]},["blocking"]);

Here I take the URL before the request and append to it the parameters of the new URL.

Where do I have to put the function and how can I call it?

Upvotes: 1

Views: 602

Answers (2)

gblazex
gblazex

Reputation: 50137

I could give you a fish but I'll teach you how to fish instead.

1) You should debug your code if it doesn't work. StackOverflow is not an online debugger.

Go to chrome://extensions/, find your extensions, click on your background page, go to the Console tab and investigate the errors you see there.

2) For one thing instead of this:

source=getUrlVars(details.url)[iapisource];

I think you what you wanted is this:

source=getUrlVars(details.url)['iapisource'];

or better yet:

var params = getUrlVars(details.url);
var redirectUrl = tab.url+"?iapisource=" + params.iapisource + "&iapiid=" + params.iapiid;

3) The tabs.get callback function will only run after you've already returned from the onBeforeRequest

// 1.
chrome.webRequest.onBeforeRequest.addListener(function(details){  
    // 2.
    chrome.tabs.get(details.tabId, function (tab) { 
      // 4.
      source=getUrlVars(details.url)[iapisource];
      id=getUrlVars(details.url)[iapiid];
      redirectUrl=tab.url+"?iapisource="+source+"&iapiid="+id;
    });
    // 3.
    return {cancel : true , redirectUrl : redirectUrl}; // redirectUrl is undefined!
  }, 
  {urls: ["*://*/*iapisource*iapiid*"]},
  ["blocking"]
);

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276586

You can use extension.getBackgroundPage to gain access to the window object of your background page which would normally contain your global functions in the background page.

This issue is further discussed here.

If you can't do that, you should look into message passing.

Upvotes: 1

Related Questions