我正在研究一种Google Chrome浏览器扩展,该扩展将所有段落(p标记内容)并将每个单词放入按钮中。这是我正在开发的一个更大程序的一部分。我在JSFiddle上有该应用程序部分的工作副本。用包含该文本的按钮替换网页段落中的每个词
现在,我试图将该代码移植到Chrome扩展程序中。但是,我无法从后台脚本访问DOM,因此可以使用我的代码操作它(在我的函数中)。我还没有调用该函数,因为我无法弄清楚我应该如何在background.js内首先编辑DOM。
这里是我的代码:
manifest.json的
{
"manifest_version": 2,
"name": "Test Extension",
"version": "1",
"background": {
"persistent": false,
"scripts": ["background.js","jquery-3.0.0.min.js","TextSplitter.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab","tabs"]
}
content.js
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document);
}
});
background.js
个// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n');
console.log(JSON.stringify(domContent));
var domAccess = $(domContent);
var myText = $(domAccess).find("p").text();
console.log("THIS IS MY TEXT: " + myText);
}
chrome.tabs.onUpdated.addListener(function (tabID, info, tab) {
console.log("Status: " + info.status);
if (info.status == "complete") {
chrome.tabs.sendMessage(tab.id, { text: 'report_back' }, doStuffWithDom);
}
});
TextSplitter.js
function FormatText(domObject) {
var pElements = []; // Holds the split paragraphs for each p tag
var pElementIndex = 0;
//Loop through each p tag in web page
$("p").each(function (webPElementIndex, webPElement) {
var jQObjWebPElement = $(webPElement);// Convert p element to jQuery Obj
// split current paragraph element text into an array of seperate words
pElements[webPElementIndex] = jQObjWebPElement.text().split(" ");
});
//Clear text out of all p elements
$("p").empty();
//Loop through p elements in the webpage to add back text with spans around each word
$("p").each(function (webPElementIndex, webPElement) {
// convert current web page element to jQuery Obj
var jQObjWebPElement = $(webPElement);
// Loop through each word stored in each stored paragraph element
$.each(pElements[pElementIndex], function (pElementWordIndex, pElementWord) {
var jQObjPElementWord = $(pElementWord); // convert element to jQuery object
jQObjWebPElement.append($("<button>")
.text(pElements[pElementIndex][pElementWordIndex]));
});
pElementIndex = pElementIndex + 1;
});
}
请原谅我的无知,我是很新的,在一般的DOM的工作,特别是在浏览器扩展程序。
请参阅[扩展概述](https://developer.chrome.com/extensions/overview#arch):您需要一个内容脚本。 – wOxxOm
删除您的后台脚本并将您的功能转移到您的内容脚本。处理和修改html应该在内容脚本中完成,因为你的后台脚本不能直接访问dom。无需传递消息 – nick