如何根据从“popup.html”中的FORM中获取的数据打开新标签?

时间:2013-06-18 14:00:30

标签: google-chrome-extension tabs

我想创建一个chrome扩展程序,它从popup.html中的“表单”获取输入,并使用popup.js打开在新选项卡中选择的网站。

的manifest.json ** **

    {
  "manifest_version": 2,

  "name": "Question Searcher",
  "description": "This extension displays the problem from popular online judges like UVA, SPOJ, Topcoder and Codeforces on serching the keyword. It also searches for a list of problems based on problem type.",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "permissions": [
    "tabs"
  ]
}

popup.html

    <!DOCTYPE html>
    <html>
    <head>
    <script src = "popup.js" > </script>
    <link rel = "stylesheet" type = "text/css" href = "theme.css" >
    </head>

    <body>

    <h1> Search </h1>
    <form name = "input">
    <p>
    Judge:
    <select name = "judge">
    <option value = "uva" selected> UVA </option>
    <option value = "spoj" > SPOJ </option>
    <option value = "tc" > Topcoder </option>
    <option value = "tcat" > Topcoder Category  </option>
    <option value = "cf" > Codeforces Category </option>
    </select>
    <input type = "text" name = "keyword"<br>
    <button type="button" onclick="return validate_register()">Go!</button> 
    </p>
    </form>
    </body>
    </html>

** ** popup.js

function validate_register()
{
    alert("beep");
    var str=document.forms["input"]["keyword"].value;
    //alert(str);
    switch(document.forms["input"]["judge"].value)
    {
        case "uva":
            return chrome.tabs.create({url: 'http://www.uva.onlinejudge.org/external/'+str.substring(0,str.length-2)+'/'+str+'.html'});
        break;
        case "spoj":
            return chrome.tabs.create({url: 'https://www.spoj.pl/problems/'+str.toUpperCase()+'/'});
        break;
        case "tc":
            return chrome.tabs.create({url: 'http://www.topcoder.com/tc?module=ProblemArchive&class='+str});
        break;
        case "tcat":
            return chrome.tabs.create({url: 'http://www.topcoder.com/tc?module=ProblemArchive&cat='+str});
        break;
        case "cf":
            return chrome.tabs.create({url: 'http://www.codeforces.com/problemset/tags/'+str});
        break;
    }

}

此代码无效。我认为问题可能出在JS文件中,在chrome.tabs.create中,但我无法弄明白。有人可以指出问题。

1 个答案:

答案 0 :(得分:0)

问题在于内容安全策略。当您将chrome v2用于chrome扩展时,它不允许在HTML代码中执行内联JavaScript。 (您可以通过右键单击BrowserAction图标来检查带有DevTools的弹出窗口。)

这就是为什么你的onclick属性不起作用的原因。要解决此问题,您需要从HTML中删除此属性,并在popup.js内添加此类代码:

window.onload = function() {
    document.querySelector('button').onclick = function(e) {
        e.preventDefault();
        validate_register();
    };
};