0

コンテンツ スクリプトから背景ページにメッセージを渡そうとしています。このエラーは、コンテンツ スクリプトの実行時に発生します。

Uncaught TypeError: Cannot call method 'sendRequest' of undefined 

コンテンツ スクリプト:

function injectFunction(func, exec) {
    var script = document.createElement("script");
    script.textContent = "-" + func + (exec ? "()" : "");
    document.body.appendChild(script);
}

function login() {

    chrome.extension.sendMessage({greeting: "hello"}, function(response) {
        console.log(response.farewell);
    });

    var d = window.mainFrame.document;
    d.getElementsByName("email")[0].value = "I need the response data here";
    d.getElementsByName("passwort")[0].value = "Here too.";
    d.forms["login"].submit();
}

injectFunction(login, true);

バックグラウンド:

 chrome.extension.onMessage.addListener(
 function(request, sender, sendResponse) {
      if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
 });

マニフェスト.json:

{
    "name": "Sephir Auto-Login",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Contact x@x.com for support or further information.",
    "options_page": "options.html",
    "icons":{
        "128":"icon.png"
    },
    "background": {
        "scripts": ["eventPage.js"]
    },
    "content_scripts": [
        {
          "matches": ["https://somewebsite/*"],
          "js": ["login.js"]
        }, 
        {
          "matches": ["somewebsite/*"],
          "js": ["changePicture.js"]
        }
    ],
     "permissions": [
        "storage",
        "http://*/*",
        "https://*/*",
        "tabs"
    ]
}

これらは google のドキュメントの例なので、うまくいくはずです。

何か助けはありますか?私は完全に迷っています。

4

2 に答える 2

2

この問題は、スクリプトの実行環境に対するあなたの誤解が原因です。詳細については、 Chrome 拡張コードとコンテンツ スクリプトと挿入されたスクリプトを参照してください。正確には、このメソッドの形式を使用して、Web ページのコンテキストでコードを実行しています。chrome.extensionWeb ページからAPIにアクセスすることはできません。

この場合は必要ないため、挿入されたスクリプトを使用しないようにコードを書き直すことをお勧めします。

function login() {

    chrome.extension.sendRequest({greeting: "hello"}, function(response) {
        console.log(response.farewell);
    });

    var d = document.getElementById('mainFrame').contentDocument;
    d.getElementsByName("email")[0].value = "I need the response data here";
    d.getElementsByName("passwort")[0].value = "Here too.";
    d.forms["login"].submit();
}

login();

*フレームが同じ原点にある場合にのみ機能します。それ以外の場合は、コードを正しく実行するためにこのメソッドが必要です。

于 2012-10-08T08:42:23.883 に答える
1

sendRequestおよび非推奨onRequestです。sendMessageonMessageを使用する必要があります。

また、関数を DOM に注入しているため、コンテンツ スクリプト コンテキストの外部で実行chrome.extensionされるため、この関数で API を使用できなくなります。

于 2012-10-08T08:38:53.337 に答える