Chrome扩展程序操作在下一个标签页上并返回上一个标签页

时间:2014-09-27 10:54:58

标签: html google-chrome google-chrome-extension

我想要将更改标签添加到下一个标签,对HTML执行某些操作(比如获取一些数据),然后返回“主要'标签。始终打开两个选项卡。我可以更改选项卡(使用background.js)它应该是活动的但是当我尝试获取HTML时它总是得到background.html ...有没有办法从第二个选项卡获取HTML代码?我想我也可以回到之前的标签'所以我真正需要的是:从第二个标签获取HTML ! (如果可能的话,我可以在html上做什么动作?)

的manifest.json

{
  "manifest_version": 2,

  "name": "name",
  "description": "desc.",
  "version": "1.0",

"background": {
  "scripts": ["background.js"]
},

"content_scripts" :[
{
  "matches":[
    "http://www.thecrims.com/*"
  ],
  "js":["contentscript.js"]
}
],

"permissions": [
  "http://www.thecrims.com/*",
  "https://www.thecrims.com/*",
  "background",
  "tabs"
],
"browser_action": {
  "default_icon": "icon.jpg"
}
}

contentscript.js 致电back.js

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response);
});

background.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {

console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
if (request.greeting == "hello")
{
    chrome.windows.getLastFocused(
         // Without this, window.tabs is not populated.
         {populate: true},
         function (window)
         {
          var foundSelected = false;
          for (var i = 0; i < window.tabs.length; i++)
          {
           // Finding the selected tab.
           if (window.tabs[i].active)
           {
            foundSelected = true;
           }
           // Finding the next tab.
           else if (foundSelected)
           {
            // Selecting the next tab.
            chrome.tabs.update(window.tabs[i].id, {active: true, selected: true});

            //GET HTML FROM ^
            chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
                console.log(tabs[0]);//this give me BACKGROUND.HTML html... i want from tabs[0]!!
            });

            return;
           }
          }
         });
  sendResponse({farewell: "goodbye"});
}
});

1 个答案:

答案 0 :(得分:1)

我想你正试图在Dev Tools中运行它来打开你的后台页面。

然后,活动窗口(由tabs.query查询)就是这样,Dev Tools窗口带有一个标签。

你为什么要运行query?您已在window.tabs[i]中使用该标签,而不是使用tabs[0]