2017-05-23 9 views
1

Google Chromeの拡張機能で、ユーザーがリンクをクリックして自動的にページにログインする必要があります。
フローは次のようにする必要があります。ユーザーがGC拡張のリンクをクリックすると、スクリプトは必要なすべてのパラメータを取り、新しく開いたタブに送信します。
私のスクリプトは、渡されたのparamsを挿入し、いくつかのアクションを行うことがあります。
しかし、私は理解していない、どのように変数をGC拡張スクリプトから新しく開いたタブに渡すことができますか?ここで
は、私がmain.jsでこれを使用するために、これまでに試した私のmanifest.jsonをChrome拡張機能から開いているタブに変数を渡す

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'", 
"content_scripts": [ 
    { 
    "js": [ "window/content.js"], 
    "matches": [ 
     "https://steamcommunity.com/login/home/?goto=", 
     "http://steamcommunity.com/*", 
     "https://steamcommunity.com/*" 
    ] 
    } 
], 
"background": { 
    "scripts": [ 
    "./scripts/back.js" 
    ] 
    }, 
"web_accessible_resources": [ 
    "popup.js", 
    "window/content.js" 
], 
"permissions": [ 
    "activeTab", 
    "tabs", 
    "<all_urls>", 
    "cookies", 
    "declarativeContent" 
] 


です:

chrome.tabs.executeScript(
    tab1.id, 
     {code: "var test =" + test 
     allFrames: true 
     }, 
     {file: "../popup.js"},) 
    }) 

しかし、クリックを行うと、スクリプトは新しいタブを開き、私が書いたすべてを実行しますが、変数 'test'は表示されません。

+0

executeScriptは、 'file'と' code'の両方が指定されているときは明らかに 'file'だけを使用します。メッセージを使用するか、単にexecuteScriptを入れ子にします。外側は 'code'を実行し、コールバックでinnerは' file'を実行します。 – wOxxOm

+0

スクリプトは拡張機能のスコープ内で実行されるため、ページに何かを書くことは非常に困難です。 'localStorage'を使うことをお勧めします。これは、あなたがしようとしていることに応じて、プロとかコンのセッションの間に存続することを覚えておいてください。 – Archer

答えて

0

それはちょうどトリッキー、難しいことではありません:あなたは、コンテンツ・スクリプトからジェクトコードを追加する必要があります。

この例を考えてみます。

inject.js

manifest.jsonを

{ 
    "manifest_version": 2, 
    "name": "My Extension", 
    "version": "1.0.0", 

    "content_scripts": [ 
    { 
     "matches": ["<all_urls>"], 
     "js": ["content.js"], 
     "run_at": "document_end", 
     "all_frames":false 
    } 
    ], 

    "web_accessible_resources": [ 
    "inject.js" 
    ] 
} 

content.js

var script = document.createElement('script'); 

script.src = chrome.extension.getURL('inject.js'); 
script.onload = function() { 
    window.postMessage({ type: "FROM_MY_EXTENSIONS", value: "123" }, "*"); 
} 

document.body.appendChild(script); 

をの

window.addEventListener("message", function(event) { if(event.data.type === 'FROM_MY_EXTENSIONS') { window._test = event.data.value; console.log('_test:', _test); } }, false); 

この拡張は、コンテンツスクリプトのメッセージからの値を持つ任意のタブに新しい_test変数を作成します。

関連する問題