使用background.js文件中的JavaScript对象在新的chrome选项卡中填充HTML

时间:2015-09-24 00:58:47

标签: javascript google-chrome google-chrome-extension

我尝试构建Chrome扩展程序,允许用户获取所有打开的网址,然后将其显示在新标签页上(最终我希望允许用户将数据发送到数据库)。我可以捕获当前窗口中的所有选项卡,但是我无法获取该数据并在新创建的选项卡中使用它。

以下是我的项目配置方式:

Manifest.json

{
  "name": "ExplodeSlideshow",
  "version": "0.0.1",
  "manifest_version": 2,
  "description" : "This Chrome extension allows you to click on all of the links in a Slideshow (opened in a New Tab) and then save those links to a database.",
  "icons": { "16": "icons/16x16.png", "48": "icons/48x48.png", "128": "icons/128x128.png" },

  "permissions": [
    "tabs"
  ],

  "browser_action": {
    "default_icon": {
      "19": "icons/19x19.png",
      "38": "icons/38x38.png"
    },
    "default_title": "That's the tool tip",
    "default_popup": "browseraction/popup.html"
  },

  "background": {
    "scripts": ["background.js", "populate_content.js"],
    "persistent": false
  },

  // "chrome_url_overrides" : {
  //   "newtab": "newtab/newtab.html"
  // },

  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"]
    }
  ]
}

background.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch(request.type) {
        case "capture-tabs":
            getWindowUrls();
        break;
    }
    return true;
});

var getWindowUrls = function() {
  // get current browser window
  chrome.windows.getCurrent(function(win) {

    // alert(JSON.stringify(win));

    // get an array of the tabs in the window
    chrome.tabs.getAllInWindow(win.id, function(tabs) {

      var activeUrl = "";
      var activeUrlId = null;
      var urls = [];

      for (i in tabs) {
        if (tabs[i].active === true) {
          // save current tab's id & URL
          activeUrl = tabs[i].url
          activeUrlId = tabs[i].id
        } else {
          // capture other tabs' id & URL
          urls.push({id: tabs[i].id, url: tabs[i].url});
        }
      }

      // alert(JSON.stringify(activeUrl));
      // alert(JSON.stringify(urls));

      // open new tab
      chrome.tabs.create({active: true, url: 'newtab/newtab.html'}, function (tab) {

        alert(JSON.stringify(tab));

        // populate HTML
        // NEED HELP HERE

        // remove original tab
        chrome.tabs.remove(activeUrlId, function() {});

        // close newly opened tabs
        for (i in urls) {
          chrome.tabs.remove(urls[i].id, function() {});
        }

      });

    });
  });

}

browseraction/popup.html

<script type="text/javascript" src="popup.js"></script>
<div style="width:200px">
    <button id="button">Capture Tabs</button>
</div>

browseraction/popup.js

window.onload = function() {
    document.getElementById("button").onclick = function() {
        chrome.extension.sendMessage({
            type: "capture-tabs"
        });
    }
}

newtab/newtab.html

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">


        <style type="text/css">

        </style>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center">Explode Slideshows | Chrome Extension</h1>
            <h4>Origin Page: <span id="origin"></span></h4>
            <ul id="other_tabs">

            </ul>
        </div>

        <script type="text/javascript" src="populate_content.js"></script>
    </body>
</html>

newtab/populate_content.js

(function() {
  var origin_element = document.getElementById("origin");
  var other_tabs_element = document.getElementById("other_tabs");

  origin_element.innerHTML += activeUrl;
})();

当我尝试使用此Chrome扩展程序时,我可以单击popup.html中的按钮,它会抓取所有选项卡,将它们存储在变量中,打开新选项卡,销毁其他选项卡。但是我无法填充新创建的标签的HTML - 我得到Uncaught ReferenceError: activeUrl is not defined.所以,我的问题是如何传递JavaScript对象(activeUrlurlsbackground.js getWindowUrls()方法并用于在我的newtab/newtab.html文件中填充HTML?

1 个答案:

答案 0 :(得分:0)

您的新标签未直接链接到背景页面。因此,您的新选项卡将无法访问存储在background.js中的任何变量。您可以使用消息传递,但我发现保存和使用窗口变量更容易:

示例新标签:

elements = Hash.new()
elements[100] = "a"
elements[200] = "b"
elements[300] = "c"
elements[400] = "d"

puts "elements: #{elements.inspect}"
puts "Count: #{elements.count()}"
elements.delete(100)
puts "elements: #{elements.inspect}"
puts "Count: #{elements.count()}"

# > elements: {100=>"a", 200=>"b", 300=>"c", 400=>"d"}
# > Count: 4
# > elements: {200=>"b", 300=>"c", 400=>"d"}
# > Count: 3

示例背景页面:

chrome.runtime.getBackgroundPage(function(window){
    var backgroundpage=window;
    backgroundpage.activeUrl;//equals "foo"
    backgroundpage.executeFunction("hi");//returns "hello!"
});

Popups也支持这一点。内容脚本不要。

让您的背景页面将所有相关信息保存到变量中。 当您的新标签加载时,让它抓住该变量并自行瞳孔化。 背景页面不应该负责对html进行伪装。