Chrome扩展程序for循环不一致

时间:2016-05-04 18:21:51

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

我遇到了目前正在处理的Chrome扩展程序问题。它的功能是从弹出文本区域获取用户输入,并为每个由换行符分隔的URL创建选项卡。总的来说,它成功地90%的时间打开所有网址,但10%的时间它只在textarea中打开7/10网址。此外,jquery 2.2.3用于获取textarea的值,不确定是否重要。

我试图弄清楚如何/为什么偶尔只会在textarea中打开7/10网址以及是否可以修复。下面是manifest,popup.html和backend.js。

backend.js:

function urltoTabs(){
var text = $('textarea').val().split('\n');
  for (var h = 0; h <= text.length; h++) {
    if (text[h].length < 1) continue;
    chrome.tabs.create({url:text[h]});
  }
}
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('engage').addEventListener('click', urltoTabs);
});

popup.html:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="jquery-2.2.3.min.js"></script>
        <script type="text/javascript" src="backend.js"></script>    
    </head>
    <body>
        <form>
            <p><strong>List urls below<strong><br />
            <textarea id="textarea" rows="15"></textarea></p>
            <button id="engage">Engage!</button>
        </form>
    </body>
</html>

的manifest.json:

{
  "manifest_version": 2,
  "name": "Link to Tabs",
  "short_name": "Link To Tabs",
  "description": "Test url to tabs.",
  "version": "0.0.4",
  "minimum_chrome_version": "38",
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["backend.js"]
    }],

  "permissions": [
          "tabs"
        ],

  "browser_action": {
          "default_icon": {                    
            "19": "assets/icon_16.png"           
          },
          "default_title": "New Tabs!",      
          "default_popup": "popup.html"        
        },

  "icons": {
    "16": "assets/icon_16.png",
    "128": "assets/icon_128.png"
  }
}

我感谢你们的任何帮助!

1 个答案:

答案 0 :(得分:0)

回复@wolf-war

问题是弹出窗口会在创建标签后关闭,这会过早关闭操作。将popup.html和backend.js推送到后台解决了这个问题。所有改变的都是manifest.json。

的manifest.json:

{
  "manifest_version": 2,
  "name": "Link to Tabs",
  "short_name": "Link To Tabs",
  "description": "Test url to tabs.",
  "version": "0.0.4",
  "minimum_chrome_version": "38",
  "background": {
    "js": "backend.js", // Needs both js and html to store user input correctly
    "page": "popup.html" 
  },
  "permissions": [
          "tabs"
        ],
        //content_scripts was removed
  "browser_action": {
          "default_icon": {                    
            "19": "assets/icon_16.png"           
          },
          "default_title": "New Tabs!",      
          "default_popup": "popup.html"        
        },

  "icons": {
    "16": "assets/icon_16.png",
    "128": "assets/icon_128.png"
  }
}

感谢所有的帮助,我真的很感激!