15

如此简单的事情怎么会如此不可能?

我要做的就是单击我的扩展程序的 browser_action 按钮,打开一个带有几个设置的表单,然后单击表单上的按钮来启动一个进程。

我一生都无法在后台表单中单击按钮来工作。

我试图让http://developer.chrome.com/extensions/contentSecurityPolicy.html#H2-3上的示例工作,但它没有。browser_action 和 background 的规则有区别吗?这就是我的事件监听器没有触发的原因吗?

有人可以提供一个工作示例吗?

清单.json:

{
    "name": "Convert",
    "version": "0.1",
    "description": "Converts the current page",
    "browser_action": {
        "default_icon": "exticon.png",
        "default_popup": "background.html"
    },
    "content_scripts": [{
        "matches": ["*://*/*"],
        "js": ["contentscript_static.js"]
    }],
    "permissions": [
        "tabs", "http://*/*", "https://*/*"
    ]
}

背景.html:

<html>
    <head>
        <title>Converter</title>
        <script src="background.js"/>
        <script>
        // Initialize the localStorage
        if (null == localStorage["htmlImport"])
           localStorage["htmlImport"] = false;

        // Called when the user clicks on the browser action icon.
        chrome.browserAction.onClicked.addListener(function(tab) {
            console.log('in listener');
                 // execute the content script
                 chrome.tabs.executeScript(null, 
                    {
                       file: "contentscript.js",
                       allFrames: true   // It doesn't work before 4.0.266.0.
                    });
              });

        // Listen to the requests from the content script
        chrome.extension.onRequest.addListener(
              function(request, sender, sendResponse)
              {
                 switch (request.name)
                 {
                    case "getPreferences":
                       sendResponse(
                          {
                             prefIgnoreLinks : localStorage["htmlImport"]
                          });
                       break;

                    case "PressShortcut":
                       sendResponse({});  // don't response.

                       // execute the content script
                       chrome.tabs.executeScript(null, 
                          {
                             file: "contentscript.js",
                             allFrames: true   // It doesn't work before 4.0.266.0.
                          });

                       break;

                    default:
                       sendResponse({});  // don't response.
                       break;
                 }
              });


        </script>
    </head>
    <body style='min-width:250px;'>
        Link depth: <input type='text' name='depth' value='3'/><br/>
        <input type='checkbox' name='changedomain'>Include external domains</input><br/>
        <button id='beginConvert'>Convert</button>
    </body>
</html>

背景.js:

function awesome() {
  // Do something awesome!
  console.log('awesome')
}
function totallyAwesome() {
  // do something TOTALLY awesome!
  console.log('totallyAwesome')
}

function awesomeTask() {
  awesome();
  totallyAwesome();
}

function clickHandler(e) {
  setTimeout(awesomeTask, 1000);
}
// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
//document.addEventListener('DOMContentLoaded', function () {
//  document.querySelector('button').addEventListener('click', clickHandler);
//});

// Add event listeners once the DOM has fully loaded by listening for the
// DOMContentLoaded event on the document, and adding your listeners to
// specific elements when it triggers.
document.addEventListener('DOMContentLoaded', function () {
//  console.log('event listener for button connected to beginConversion()');
    //document.querySelector('button').addEventListener('click', beginConversion);
    document.getElementById('beginConvert').addEventListener('click', clickHandler);
});
4

2 回答 2

53

你的目标

  • 点击扩展按钮
  • 扩展弹出窗口与控件一起打开
  • 根据扩展弹出窗口中的控件在当前选项卡上执行脚本

尖端

  • 将背景页面视为控制中心。它从您的 Chrome 扩展程序中的各种脚本接收传入请求,具有更高的权限来执行跨域请求(如果在清单中定义)等等。
  • 您应该使用清单版本 2,因为不推荐使用版本 1。
  • Manifest 版本 2 不允许内联脚本,因此所有脚本都需要作为自己的文件加载。

例子

清单.json

{
    "name": "Stackoverflow Popup Example",
    "manifest_version": 2,
    "version": "0.1",
    "description": "Run process on page activated by click in extension popup",
    "browser_action": {
        "default_popup": "popup.html"
    },
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": [
        "tabs", "http://*/*", "https://*/*"
    ]
}

背景.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        switch (request.directive) {
        case "popup-click":
            // execute the content script
            chrome.tabs.executeScript(null, { // defaults to the current tab
                file: "contentscript.js", // script to inject into page and run in sandbox
                allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
            });
            sendResponse({}); // sending back empty response to sender
            break;
        default:
            // helps debug when request directive doesn't match
            alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
        }
    }
);

popup.html

<html>
    <head>
        <script src="popup.js"></script>
        <style type="text/css" media="screen">
            body { min-width:250px; text-align: center; }
            #click-me { font-size: 20px; }
        </style>
    </head>
    <body>
        <button id='click-me'>Click Me!</button>
    </body>
</html>

popup.js

function clickHandler(e) {
    chrome.runtime.sendMessage({directive: "popup-click"}, function(response) {
        this.close(); // close the popup when the background finishes processing request
    });
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('click-me').addEventListener('click', clickHandler);
})

内容脚本.js

console.log("chrome extension party!");

运行示例截图

在浏览器窗口打开到 exampley.com 的情况下单击扩展按钮

在浏览器窗口打开到 exampley.com 的情况下单击扩展按钮

点击“点击我!”后 扩展弹出窗口中的按钮

点击“点击我!”后  扩展弹出窗口中的按钮


zip 中的示例文件

http://mikegrace.s3.amazonaws.com/stackoverflow/detect-button-click.zip

于 2012-08-16T23:47:07.233 回答
3

以前的答案不再起作用,我花了几个小时才了解如何管理解决方法。我希望这能让你比我走得更快。

首先,你是这个页面中的最后一个方法(在页面底部),它是异步的,所以记得给它一个回调。您需要的代码是这样的 smtg:

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.query({'active': true}, getActiveTabCallback);
});

其次,您需要了解一件让我费时费力的事情:如果您不使用背景 html 页面,您将无法console.log在 Chrome 主窗口中看到任何内容。您需要转到扩展页面 ( chrome://extensions) 并单击您的扩展background page链接(是的,您没有背景页面,但 Chrome 为您提供了一个假的)。这种类型的扩展(基于事件)应该具有包含 smtg 的 manifest.json,如下所示:

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

问候!

于 2014-03-15T03:05:29.730 回答