0

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

**清单.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;
    }

}

此代码不起作用。我认为问题可能出在 chrome.tabs.create 中的 JS 文件中,但我无法弄清楚。有人可以指出问题所在。

4

1 回答 1

0

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

所以这就是你的onclick属性不起作用的原因。要解决此问题,您需要从 HTML 中删除此属性,并在其中添加如下代码popup.js

window.onload = function() {
    document.querySelector('button').onclick = function(e) {
        e.preventDefault();
        validate_register();
    };
};
于 2013-06-19T13:43:34.237 回答