2016-07-29 61 views
0

JavaScript新手,決定試用Chrome擴展。我試圖將items數組傳遞給我的html文件,但它在我的Chrome擴展中的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')什麼也得不到,使用document.querySelector('p')document.querySelector('#target')
  2. 當創建hello.htmlpopup.html已經關閉,所以當你打電話chrome.runtime.sendMessage發送消息,其實這個消息通道的另一端沒有打開的。這就是爲什麼您在回調中獲得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) –