我该怎么做? (Chrome扩展程序)

时间:2014-10-12 02:00:57

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

我是创建扩展程序的新手,我正试图让它们变得更加舒适。基本上,我试图创建一个简单的扩展来执行以下操作:

  1. 打开一个新窗口(已实现)。
  2. 有能力点击'扩展中的按钮(未实现)。
  3. 我不确定如何使用扩展程序点击新窗口中的按钮。我怎么处理这个?这就是我现在所拥有的:

    popup.html

    <html>
            <body>
                    <input type="button" id="the_button" value="My button"></input>
            </body>
            <script src="popup.js"></script>
    </html>
    

    popup.js

    document.getElementById("the_button").addEventListener("click", function() {
        var win = window.open("http://www.roblox.com", "roblox", 400, 400)
        //Now what can I do to externally click buttons?
    })
    

    manifest.json

    {
      "manifest_version": 2,
      "name": "Test",
      "description": "Test Extension",
      "version": "1.0",
    
      "icons": { 
        "48": "icon.png"
       },
    
      "permissions": [
        "http://*/*", 
        "https://*/*"
      ],
    
      "content_scripts": [{
        "matches": ["http://*/*", "http://*/*"],
        "js": ["jquery.js", "popup.js"]
      }],
    
      "browser_action": {
        "default_title": "This is a test",
        "default_icon": "icon.png",
        "default_popup": "popup.html"
      }
    }
    

2 个答案:

答案 0 :(得分:1)

首先,您使用</input>结束标记时出错: <input>标记不需要关闭!所以更改您的{{1进入这个:

popup.html

现在,回到真正的问题:

您需要创建一个新选项卡,然后将内容脚本注入页面。 以下是一个快速解决方案:

  1. <html> <body> <input type="button" id="the_button" value="My button"> </body> <script src="popup.js"></script> </html> 权限添加到tabs

    manifest.json

    从清单中删除... "permissions": [ "*://*/*", // this will match both http and https :) "tabs" ], ... 内容脚本,这没用!你不需要它。

    popup.js

    警告:当我说删除时,我的意思是从您的... "content_scripts": [{ // remove! "matches": ["http://*/*", "http://*/*"], // remove! "js": ["jquery.js", "popup.js"] // remove! }], // remove! ... 中删除该行,请勿使用评论(manifest.json)并执行操作不要将我的代码复制并粘贴到您的代码上,只需删除这四行。

  2. 现在,在您的//中,当您打开标签页时,可以在页面中注入内容脚本,如下所示:

    popup.js
  3. 这将创建一个新选项卡,并在其中注入脚本document.getElementById("the_button").addEventListener("click", function() { chrome.tabs.open({url:"http://www.roblox.com", active:"true"}, function(tab) { chrome.tabs.executeScript(tab.id, {file:"click_the_button.js", run_at: "document_end"}); // here is where you inject the content script ^^ } }); ,您将使用该脚本单击页面内的按钮(加载时),其代码为:

    click_the_button.js
  4. 注意:如果你想在你的var thing = $("a#roblox-confirm-btn"); thing.click(); 脚本中使用jQuery,你可以在它之前的标签中注入它:

    click_the_button.js

    您可能会觉得有用的资源:

答案 1 :(得分:-1)

您需要制表符权限。 我之前遇到过同样的问题。 答案在这里:

Chrome extension; open a link from popup.html in a new tab

相关问题