2016-07-29 4 views
0

javascriptが新しく、クロム拡張機能を使用することに決めました。私はアイテムの配列をHTMLファイルに渡そうとしていますが、クロム拡張のhtmlで定義されていないものとして表示されています。ボタン/ポップアップのjsファイルからローカルのhtmlファイルに行うことは可能ですか?ここで私が持っているものです。popup.jsからローカルのhtmlページにオブジェクトを送信

manifest.jsonを

{ 
    "manifest_version": 2, 
    "name": "Testing", 
    "short_name": "Testing", 
    "version": "1", 
    "browser_action": { 
    "default_popup": "./button.html" 
    }, 
    "permissions": [ 
    "activeTab", 
    "<all_urls>" 
    ] 
} 

Popup.js

var items = {}; 
var type = ["1","2","3"]; 
type.forEach(function(type,index){ 
    //code to store stuff into items array 
} 
console.dir(items) //shows everything was stored correctly 

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    if(request.action == "getData") { 
     sendResponse(items); 
    } 
    return true; 
}); 

chrome.tabs.create({url: './hello.html', selected:true}); 

hello.html

<!doctype html> 
<html lang="en"> 
<head> 
    <script src="./pasteData.js"></script> 
</head> 
<body> 
<p id="target">PARAGRAPH</p> 
</body> 
</html> 

pasteData.js

function getData() { 
    chrome.runtime.sendMessage({"action": "getData"}, function(data) { 
     document.getElementById("target").innerHTML = data; 
    }); 
}; 

window.onload = function() { 
    document.querySelector('button').onclick = function(e) { 
     e.preventDefault(); 
     getData(); 
    }; 
}; 

答えて

1
  1. document.querySelector('button')は、何を取得しますが、実際には、このメッセージチャネルのもう一方の端を、メッセージを送信するためにchrome.runtime.sendMessageを呼び出すときdocument.querySelector('p')または
  2. hello.htmlが作成されると、popup.htmlが閉じられたdocument.querySelector('#target')が、そうではすべての開いていないされて使用されます。そのため、undefinedをコールバックに追加すると、message passingロジックをpopup.jsからEvent pageに移動するか、代わりにchrome.storageのようなものを使用してみてください。
+0

ロジックを移動する代わりに、popup.jsのデータをイベントページに渡して、そこからhtmlページを取得できますか? – CodingNinjaInTraining

+0

popup.jsとイベントページの両方が拡張コンテキストに存在する場合、['chrome.runtime.getBackgroundPage'](https://developer.chrome.com/extensions/runtime#method- getBackgroundPage) –

関連する問題