Sum*_*och 82 html javascript jquery google-chrome google-chrome-extension
我知道这已经在很多帖子中被问过,但说实话,我没有得到它们.我是JavaScript,Chrome扩展程序以及所有内容的新手,我有这个课程作业.所以我需要创建一个插件,使用跨域请求计算任何给定页面上的DOM对象.到目前为止,我已经能够使用Chrome Extension API实现这一目标.现在问题是我需要在contentScript.js文件中的popup.html页面上显示数据.我不知道该怎么做我已经尝试阅读文档但是在chrome中发送消息我只是无法理解该怎么做.
以下是到目前为止的代码.
的manifest.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/*"
]
Run Code Online (Sandbox Code Playgroud)
popup.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>
Run Code Online (Sandbox Code Playgroud)
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;
});
Run Code Online (Sandbox Code Playgroud)
popup.js
$(function (){
$('#readDom').click(function(){
chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "readDom"});
});
});
});
Run Code Online (Sandbox Code Playgroud)
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
});
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,请避免我做的任何noobness :)
gka*_*pak 156
虽然你肯定是在正确的方向(并且实际上非常接近结束),但是你的代码中有几个(imo)不良实践(例如,为这样一个简单的任务注入一个完整的库(jquery),声明不必要的权限,使得超级调用API方法等).
我自己没有测试你的代码,但是从快速概述我认为纠正以下内容可能会产生一个有效的解决方案(虽然不是非常接近最优):
在manifest.json中:更改内容脚本的顺序,首先放置jquery.根据相关文件:
"js"[...]要注入匹配页面的JavaScript文件列表.它们按照它们在此数组中出现的顺序注入.
(强调我的)
在contentscript.js中:将chrome.runtime.sendMessage({...})块移动到onMessage
侦听器回调中.
那就是说,这是我提出的方法:
root-directory/
|_____img
|_____icon19.png
|_____icon38.png
|_____manifest.json
|_____background.js
|_____content.js
|_____popup.js
|_____popup.html
Run Code Online (Sandbox Code Playgroud)
{
"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": []
}
Run Code Online (Sandbox Code Playgroud)
chrome.runtime.onMessage.addListener((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);
}
});
Run Code Online (Sandbox Code Playgroud)
// 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((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);
}
});
Run Code Online (Sandbox Code Playgroud)
// Update the relevant fields with the new data.
const 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', () => {
// ...query for the active tab...
chrome.tabs.query({
active: true,
currentWindow: true
}, 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);
});
});
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)
我会给你一个简单的解决方案
问题是如何将消息从内容脚本发送到弹出窗口而不是弹出窗口到内容脚本
在弹出窗口中,您必须从弹出窗口发送消息
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type:"msg_from_popup"}, function(response){
alert(response)
});
});
})
Run Code Online (Sandbox Code Playgroud)
在内容脚本中,您必须添加事件侦听器,但问题是您必须返回 true这意味着您可以异步使用 sendResponse 如果您没有提到 return true 它将同步工作您必须立即返回 sendResponse 消息
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request["type"] == 'msg_from_popup'){
console.log("msg receive from popup");
sendResponse("msg received and sending back reply");// this is how you send message to popup
}
return true; // this make sure sendResponse will work asynchronously
}
);
Run Code Online (Sandbox Code Playgroud)
您可以为此使用localStorage。您可以将哈希表格式的任何数据存储在浏览器内存中,然后随时访问。我不确定我们是否可以从内容脚本访问本地存储(之前已被阻止),请尝试自己完成。这是通过后台页面执行操作的方法(我先将数据从内容脚本传递到后台页面,然后将其保存在localStorage中):
在contentScript.js中:
chrome.runtime.sendMessage({
total_elements: totalElements // or whatever you want to send
});
Run Code Online (Sandbox Code Playgroud)
在eventPage.js(您的背景页面)中:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
localStorage["total_elements"] = request.total_elements;
}
);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用localStorage [“ total_elements”]在popup.js中访问该变量。
也许您可以在现代浏览器中直接从内容脚本访问localStorage。然后,您无需通过后台页面传递数据。
关于localStorage的不错的阅读:http : //diveintohtml5.info/storage.html
归档时间: |
|
查看次数: |
75381 次 |
最近记录: |