简体   繁体   English

Chrome扩展程序:为什么不起作用?

[英]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. 我试图获取chrome中选项卡的当前URL,然后向站点发起请求并获取内容并将其写入文档主体。 Here's my chrome ext. 这是我的chrome ext。 js: 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 但这会抛出:响应tabs.query时出错:TypeError:未定义不是函数... bla bla

What I'm doing wrong? 我做错了什么? What is the best approach? 最好的方法是什么?

EDIT: 编辑:

Here's My Manifest.json: 这是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"
  ]
}

"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. “ TypeError:未定义不是函数”表示您正在尝试调用具有undefined值的东西,就好像它是一个函数一样。

In your case, you call this.connect(urlfinal) , but this is not what you expect it to be (not engine ). 在你的情况,你叫this.connect(urlfinal)但是this是不是你希望它是(不是engine )。

You are inside a callback, not your run function anymore , and this has no property connect . 位于回调内部,而不再是run函数 ,并且this没有属性connect Therefore, this.connect == undefined . 因此, this.connect == undefined In these circumstances, calling this.connect() throws that error. 在这种情况下,调用this.connect()会引发该错误。

To solve this, you can, for instance, store the top level this object, and let closures take care of the rest: 为了解决这个问题,例如,您可以存储this对象的顶层,并让闭包处理其余的对象:

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 . 此处查看有关此技术的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM