Mehul
Mehul

Reputation: 21

Chrome Extension: Why Isn't It Working?

I'm trying to get the current URL of the tab in chrome and then initiate a request to a site and get content back and write it to document body. Here's my chrome ext. js:

var engine = {

    run: function () {
        chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        }, function (tabs) {
            var url = tabs[0].url;
            var urlfinal = 'http://SOMESITEHERE.com/api.php?url=' + url;
            var response = this.connect(urlfinal);
            document.write(response);
        });
    },



    //console.log(this.url),

    connect: function (link) {
        var xmlHttp = null;
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", link, false);
        xmlHttp.send(null);
        return xmlHttp.responseText;
    }

};

document.addEventListener('DOMContentLoaded', function () {
    engine.run();
});

But this throws: Error in response to tabs.query: TypeError: undefined is not a function ... bla bla

What I'm doing wrong? What is the best approach?

EDIT:

Here's My Manifest.json:

{
  "manifest_version": 2,

  "name": "SOMETHINGHERE",
  "description": "SOMETHINGHERE",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "http://SITEHERE.com/",
    "tabs"
  ]
}

Upvotes: 1

Views: 889

Answers (1)

Xan
Xan

Reputation: 77482

"TypeError: undefined is not a function" means that you're trying to call something that has the value undefined as if it was a function.

In your case, you call this.connect(urlfinal), but this is not what you expect it to be (not engine).

You are inside a callback, not your run function anymore, and this has no property connect. Therefore, this.connect == undefined. In these circumstances, calling this.connect() throws that error.

To solve this, you can, for instance, store the top level this object, and let closures take care of the rest:

run: function () {
    var _this = this;
    chrome.tabs.query({
        'active': true,
        'windowId': chrome.windows.WINDOW_ID_CURRENT
    }, function (tabs) {
        var url = tabs[0].url;
        var urlfinal = 'http://SOMESITEHERE.com/api.php?url=' + url;
        var response = _this.connect(urlfinal);
        document.write(response);
    });
}

See more information on this technique here.

Upvotes: 1

Related Questions