我建立了一个镀铬扩展程序。
在这部分代码中,我尝试在加载页面中找到段落,对于id为load和detail的div中的每个段落,我搜索findCheckedFact
的值是否在该段落内如果是,我剪切我想将该文本放入红色的范围。
findCheckedFact
是一个字符串。这里在+'console.log("Print:", str_p, " Fact:", findCheckedFact);'
中定义了段落内的文本但是没有定义参数findCheckedFact,所以我不能通过它?
这个函数我试着调用findTextInsideParagraphs("test");
。
function findTextInsideParagraphs(findCheckedFact){
chrome.tabs.executeScript({file: "js/jquery-1.12.0.min.js"}, function() {
chrome.tabs.executeScript({"code":
'(function(findCheckedFact){'
+'$("#lead, #detail").find("p").each(function() {'
+'var str_p = $(this).text();'
+'console.log("Print:", str_p, " Fact:", findCheckedFact);'
+'if (str_p.indexOf( findCheckedFact) >= 0) {'
+'console.log("Yes kest");'
+'$(this).html($(this).html().replace(findCheckedFact, "<span class=\'red\'> $& </span>"));'
+'}'
+'});'
+'}(' + JSON.stringify("Fact: " , findCheckedFact) + '));'
});
});
}
这个函数我试过调用findTextInsideParagraphs(&#34; test&#34;); 在manifest.json中,我确实添加了所有可能的功能:
"content_scripts": [
{
"matches": [
"<all_urls>",
"http://*/*",
"https://*/*"
],
"css": [
"custom-css.css"
],
"js": [
"js/jquery-1.12.0.min.js"
],
"run_at": "document_start"
}],
"background": {
"persistent": false,
"scripts": [
"js/jquery-1.12.0.min.js",
"background.js",
"popup.js",
"blic-fact-checker.js"
],
"css":["custom-css.css"]
},
"permissions": [
"background",
"notifications",
"contextMenus",
"storage",
"tabs",
"activeTab",
"http://localhost:5000/*",
"chrome-extension://genmdmadineagnhncmefadakpchajbkj/blic-fact-checker.js",
"chrome-devtools://devtools/bundled/inspector.html?&remoteBase=https://chrome-devtools-frontend.appspot.com/serve_file/@202161/&dockSide=undocked",
"http://*/*",
"https://*/*",
"<all_urls>"
],
有人可以帮助我吗,我真的无法找到正在发生的事情?
答案 0 :(得分:1)
首先,阅读this explanation of different kinds of javascript code in Chrome extensions
如您所见,executeScript
中的代码是一个内容脚本,它无法直接访问后台和其他正确扩展页中的代码。您有3个主要选项:
1)使用FindCheckedFact
或sendMessage
将您的port.postMessage
发送到内容脚本。当然,在您的内容脚本中,您必须为它们建立侦听器,并将实际代码放在这些侦听器中。
2)将您的变量保存在本地或同步存储中,将executeScript
放入回调中,并从内容脚本中读取它们。如果您有时需要重新阅读它,请在内容脚本中为存储更改设置一个侦听器。
这些解决方案适用于.js文件中的内容脚本和内联内容脚本。但是,既然你选择内联,并且你只需要以一种方式发送值,那么你可以
3)只需将FindCheckedFact
(使用JSON.stringify或toString)字符串化,然后使用+:
chrome.tabs.executeScript({"code":
'(function('+strFindCheckedFact+'){'
等。