我可以从控制台访问对象,但不能从页面java脚本

时间:2017-02-15 20:33:43

标签: javascript google-chrome-extension undefined

我正在编写chrome扩展名,当我写入控制台时 “g_ActiveInventory”我得到了结果:

result

但是当我尝试在我的扩展程序中使用此代码获取对象时:

window.setTimeout(test2, 5000);
function test2()
{
    var size = Object.keys(g_ActiveInventory.rgInventory).size();    
    console.log(size);
}

我收到错误:

  

未捕获的ReferenceError:未定义g_ActiveInventory

我该如何解决?

的manifest.json:

{
    "name": "How Many Items",
    "version": "1.0",
    "manifest_version": 2,
    "description": "",
    "icons":    {
        "16": "icons/love.png"
    },
             "background": {
        "scripts": [
            "node_modules/jquery/dist/jquery.min.js"           
        ],
        "persistent": true
    },
    "browser_action": {
        "default_icon": "icons/love.png",
        "default_title": "How Many Items"
    },
    "content_scripts":  [ {
    "js": [ "js/jquery/jquery-1.10.2.min.js", "js/code.js" ],
      "matches": [ "*://steamcommunity.com/tradeoffer/*" ],
      "run_at": "document_end"
      } ]
}

3 个答案:

答案 0 :(得分:1)

正如文档所述(请参阅herehere),您的内容脚本无法直接访问网页的窗口对象或变量。但是,您可以尝试这个小技巧:在页面的DOM中创建一个包含所需代码的新script标记。例如:

setTimeout(test2,5000);
function test2() {
  var myScript = document.createElement("script");
  myScript.innerHTML = `
    var size = Object.keys(g_ActiveInventory.rgInventory).size();
    console.log(size)`;
  document.body.appendChild(myScript);
}

答案 1 :(得分:-1)

在调用 test2

之前,您应该定义 g_ActiveInventory

检查此代码:

function function_name() {
  console.log(size);
}


function_name();//it gives undefined because teh variable defined atfer calling

 var size="12";

这是正确的方式

 function function_name() {
  console.log(size);
}

var size="12";
function_name();//it gives 12 because the variable defined before calling

我希望这会有所帮助

答案 2 :(得分:-1)

对象可能会在5秒内加载,或者在您尝试使用时无法使用。

您可以在使用之前测试变量,如果尚未加载,请等待再试一次,如下例所示:

setTimeout(test2,5000);
function test2()
{
    if (!g_ActiveInventory){
       console.log("Not loaded yet...");
       setTimeout(test2,1000);
       return;
    }
    var size = Object.keys(g_ActiveInventory.rgInventory).size();    
    console.log(size);
}
相关问题