Расширение Chrome как отправить данные из сценария содержимого во всплывающее окно.формат html
Я знаю, что это было задано в многочисленных сообщениях, но, честно говоря, я их не получаю. Я новичок в JavaScript, расширениях Chrome и все такое, и у меня есть это назначение класса.
Поэтому мне нужно сделать плагин, который будет подсчитывать объекты DOM на любой заданной странице с помощью междоменных запросов.
Я был в состоянии достичь этого до сих пор с помощью Chrome Extension API.
Теперь проблема мне нужно показать данные на моем окне.html-страница из contentScript.js файл.
Я не знаю, как это сделать, я пробовал читая документацию, но обмен сообщениями в chrome я просто не могу понять, что делать.
следующий код до сих пор.
манифест.json
{
"manifest_version":2,
"name":"Dom Reader",
"description":"Counts Dom Objects",
"version":"1.0",
"page_action": {
"default_icon":"icon.png",
"default_title":"Dom Reader",
"default_popup":"popup.html"
},
"background":{
"scripts":["eventPage.js"],
"persistent":false
},
"content_scripts":[
{
"matches":["http://pluralsight.com/training/Courses/*", "http://pluralsight.com/training/Authors/Details/*", "https://www.youtube.com/user/*", "https://sites.google.com/site/*", "http://127.0.0.1:3667/popup.html"],
"js":["domReader_cs.js","jquery-1.10.2.js"]
//"css":["pluralsight_cs.css"]
}
],
"permissions":[
"tabs",
"http://pluralsight.com/*",
"http://youtube.com/*",
"https://sites.google.com/*",
"http://127.0.0.1:3667/*"
]
всплывающее окно.HTML-код
<!doctype html>
<html>
<title> Dom Reader </title>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<script src="popup.js" type="text/javascript"></script>
<body>
<H1> Dom Reader </H1>
<input type="submit" id="readDom" value="Read DOM Objects" />
<div id="domInfo">
</div>
</body>
</html>
eventPage.js
var value1,value2,value3;
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "show") {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.pageAction.show(tabs[0].id);
});
}
value1 = request.tElements;
});
всплывающее окно.js
$(function (){
$('#readDom').click(function(){
chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "readDom"});
});
});
});
contentScript
var totalElements;
var inputFields;
var buttonElement;
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse){
if(request.action == "readDom"){
totalElements = $("*").length;
inputFields = $("input").length;
buttonElement = $("button").length;
}
})
chrome.runtime.sendMessage({
action: "show",
tElements: totalElements,
Ifields: inputFields,
bElements: buttonElement
});
любая помощь будет оценена и, пожалуйста, избегайте любого noobness я сделал :)
2 ответов:
хотя вы определенно находитесь в правильном направлении (и на самом деле довольно близко к концу), в вашем коде есть несколько (imo) плохих практик (например, инъекция целой библиотеки (jquery) для такой тривиальной задачи, объявление ненужных разрешений, выполнение сверхвысоких вызовов методов API и т. д.).
Я не тестировал ваш код сам, но из краткого обзора я считаю, что исправление следующего может привести к рабочему решению (хотя и не очень близко к оптимальный):
на манифест.json: изменить порядок контент, скрипты, поставив на jQuery в первую очередь. Согласно соответствующие документы:
"js" [...] Список файлов JavaScript, которые будут введены в соответствующие страницы. Они вводятся в порядке в этом массиве.
(выделено мной)
In contentscript.js: перемещение хром.во время выполнения.вызов sendMessage.{(..}) блок внутри the
onMessageобратный вызов слушателя.
что сказал, Вот мой подход:
управление потоком:
- сценарий контента вводится на каждую страницу, соответствующую некоторым критериям.
- после ввода скрипты содержимого отправляют сообщение на страницу событий (непостоянная фоновая страница) и страница события присоединяет к вкладке действие page=.
- как только всплывающее окно page-action загружается, оно отправляет сообщение в сценарий содержимого, запрашивая необходимую информацию.
- сценарий содержимого обрабатывает запрос и отвечает, чтобы всплывающее окно page-action могло отображать информацию.
структура:root-directory/ |_____img |_____icon19.png |_____icon38.png |_____manifest.json |_____background.js |_____content.js |_____popup.js |_____popup.html
манифест.json:
{ "manifest_version": 2, "name": "Test Extension", "version": "0.0", "offline_enabled": true, "background": { "persistent": false, "scripts": ["background.js"] }, "content_scripts": [{ "matches": ["*://*.stackoverflow.com/*"], "js": ["content.js"], "run_at": "document_idle", "all_frames": false }], "page_action": { "default_title": "Test Extension", //"default_icon": { // "19": "img/icon19.png", // "38": "img/icon38.png" //}, "default_popup": "popup.html" } // No special permissions required... //"permissions": [] }
фон.js:
chrome.runtime.onMessage.addListener(function (msg, sender) { // First, validate the message's structure if ((msg.from === 'content') && (msg.subject === 'showPageAction')) { // Enable the page-action for the requesting tab chrome.pageAction.show(sender.tab.id); } });
содержание.js:
// Inform the background page that // this tab should have a page-action chrome.runtime.sendMessage({ from: 'content', subject: 'showPageAction' }); // Listen for messages from the popup chrome.runtime.onMessage.addListener(function (msg, sender, response) { // First, validate the message's structure if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) { // Collect the necessary data // (For your specific requirements `document.querySelectorAll(...)` // should be equivalent to jquery's `$(...)`) var domInfo = { total: document.querySelectorAll('*').length, inputs: document.querySelectorAll('input').length, buttons: document.querySelectorAll('button').length }; // Directly respond to the sender (popup), // through the specified callback */ response(domInfo); } });
всплывающее окно.js:
// Update the relevant fields with the new data function setDOMInfo(info) { document.getElementById('total').textContent = info.total; document.getElementById('inputs').textContent = info.inputs; document.getElementById('buttons').textContent = info.buttons; } // Once the DOM is ready... window.addEventListener('DOMContentLoaded', function () { // ...query for the active tab... chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { // ...and send a request for the DOM info... chrome.tabs.sendMessage( tabs[0].id, {from: 'popup', subject: 'DOMInfo'}, // ...also specifying a callback to be called // from the receiving end (content script) setDOMInfo); }); });
всплывающее окно.html:
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="popup.js"></script> </head> <body> <h3 style="font-weight:bold; text-align:center;">DOM Info</h3> <table border="1" cellpadding="3" style="border-collapse:collapse;"> <tr> <td nowrap>Total number of elements:</td> <td align="right"><span id="total">N/A</span></td> </tr> <tr> <td nowrap>Number of input elements:</td> <td align="right"><span id="inputs">N/A</span></td> </tr> <tr> <td nowrap>Number of button elements:</td> <td align="right"><span id="buttons">N/A</span></td> </tr> </table> </body> </html>
Вы можете использовать localStorage для этого. Вы можете хранить любые данные в формате хэш-таблицы в памяти браузера, а затем получить к нему доступ в любое время. Я не уверен, что мы можем получить доступ к localStorage из сценария контента (он был заблокирован раньше), попробуйте сделать это самостоятельно. Вот как это сделать через фоновую страницу (сначала я передаю данные из сценария контента на фоновую страницу, а затем сохраняю их в localStorage):
в contentScript.js:
chrome.runtime.sendMessage({ total_elements: totalElements // or whatever you want to send });в eventPage.js (ваш фон страница):
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){ localStorage["total_elements"] = request.total_elements; } );затем вы можете получить доступ к этой переменной в окне.js с localStorage ["total_elements"].
возможно, вы можете получить доступ к localStorage непосредственно из сценария содержимого в современных браузерах. Тогда вам не нужно передавать данные через фоновую страницу.
приятно читать о localStorage:http://diveintohtml5.info/storage.html
Comments