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://*/*"
    ]
}

background.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>

background.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 拡張機能のさまざまなスクリプトからの受信リクエストを受け取り、クロスドメイン リクエスト (マニフェストで定義されている場合) などを実行する権限を昇格させます。
  • バージョン 1 は非推奨であるため、マニフェスト バージョン 2を使用する必要があります。
  • マニフェスト バージョン 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://*/*"
    ]
}

background.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);
})

contentscript.js

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

実行例のスクリーンショット

exampley.com を開いたブラウザ ウィンドウで拡張ボタンをクリックする

exampley.com を開いたブラウザ ウィンドウで拡張ボタンをクリックする

「Click Me!」をクリックした後 拡張ポップアップのボタン

「Click Me!」をクリックした後  拡張ポップアップのボタン


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);
});

次に、時間がかかった 1 つのことを理解する必要があります。背景の html ページを使用していない場合console.log、メインの Chrome ウィンドウには何も表示されません。拡張ページ ( chrome://extensions) に移動し、拡張機能のbackground pageリンクをクリックする必要があります (はい、背景ページはありませんが、Chrome は偽のページを表示します)。このタイプの拡張 (イベントに基づく) には、次のような smtg を含む manifest.json が必要です。

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

よろしく!

于 2014-03-15T03:05:29.730 に答える