2015-07-11 29 views
0

我想要顯示我在後臺獲取的數據按鈕時單擊的數組數據按鈕,但沒有做任何事情時,我點擊按鈕是非常新的Chrome瀏覽器分機。謝謝。如何從背景中獲取數據在彈出頁面中顯示

的manifest.json:

{ 
    "name":"modz", 
    "manifest_version":2, 
    "version":"1.0", 
    "description":"this ext. will help you record all the urls you have visited", 

    "background": { 
    "scripts": ["background.js"] 

    }, 

    "browser_action": 
    { 
    "default_icon":"icon.png", 
    "default_popup":"popup.html" 
    }, 

    "permissions":[ 
      "tabs" 
     ] 

} 

background.js:

var data=[]; 
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    var url = tab.url; 
    if (url!=="undefined" && changeInfo.status=="complete") 
    { 
    data.push (tab.url); 
    alert(data.length); 
    } 
    } 

); 
chrome.runtime.onMessage.addListener(function(message,sender,sendrespose){ 
//send the array data back 
}); 

popup.js:

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('btn').addEventListener('click',function(){ 
    chrome.runtime.sendMessage("getdata"); 
    }); 
}); 

popup.html

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="C:\Users\modz\Desktop\modz_extention\popup.js"></script> 
    <style type="text/css"> 
    body{ 
     width:440px; 
    } 
    </style> 
</head> 
<body> 
<input id="btn" type="button" value="get data" /> 
<div id="data"></div> 

</body> 
</html> 
+0

在[sendMessage](https://developer.chrome.com/extensions/runtime#method-sendMessage)中包含對數據執行某些操作的響應函數。然後background.js調用'sendrespose(data)'。 – Teepeemm

+0

可以請給我一個代碼片段,因爲我很新的鉻合金分機和按鈕dosent工作可以請你幫我,謝謝你 –

+0

我會推薦[這個答案](http://stackoverflow.com/a/ 16325442/2336725)或[此問題](http://stackoverflow.com/q/16066317/2336725)。 – Teepeemm

回答

2

消息的官方參考是here。在你的情況,你會希望background.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ 
    sendResponse({"dataArray":data}); 
}); 

popup.js將有

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('btn').addEventListener('click',function(){ 
     chrome.runtime.sendMessage({},function(response){ 
      document.getElementById("data").textContent = response.dataArray.toString(); 
     }); 
    }); 
}); 

這也將在內容腳本工作。但是,如果內容腳本以默認document_end運行,則不需要DOMContentLoaded事件,因爲document_end之後發生。

這實際上是發送一個空的消息(空對象{})。如果你想發送不同的消息,你會想改變它。這也是爲什麼message未在background.js中使用。

既然您不是真的發送消息,另一種方法是使用getBackgroundPagebackground.js不需要監聽器,並popup.js將有:

chrome.runtime.getBackgroundPage(function(backgroundWindow){ 
    document.getElementById("data").textContent = backgroundWindow.data.toString(); 
}); 

兩件事:

  • popup.html不能使用絕對路徑popup.js。將兩者都放在擴展目錄中,並使用相對路徑:src="popup.js"

  • Google建議您將背景頁切換爲event pages。最大的區別在於,事件頁面中不能包含全局變量data(可以,但在事件頁面重新加載時會重置)。如果您無法正常工作,建議您將擴展程序作爲後臺頁面,然後發佈另一個問題。

相關問題