我要写的是一个简单的chrome扩展程序,它将检查当前显示的网站上是否存在某些单词。
我遇到的问题是js文件。我敢肯定,他们不会按预期的方式工作,但是更糟糕的是,没有能力对其进行测试。扩展按钮始终指出该词在网站上不存在(为简化起见,我使用的是“ Wikipedia”,我在Wikipedia网站上对其进行了测试,但这可以是任何东西。
content.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action === "checkForWord") {
checkForWord(request, sender, sendResponse);
return true;
}
}
);
function checkForWord(request, sender, sendResponse){
var scripts = document.getElementByTagName("*");
for (var i=0;i<scripts.length;i++) {
if (scripts[i].indexOf("Wikipedia")>-1){
return sendResponse(true);
}
}
return sendResponse(false);
}
popup.js
document.addEventListener("DOMContentLoaded", function(event) {
var resultsButton = document.getElementById("getResults");
resultsButton.onclick = getResults;
});
function getResults(){
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { action: "checkForWord" }, function (response) {
showResults(response);
});
});
}
function showResults(results) {
var resultsElement = document.getElementById("results");
resultsElement.innerText = results ? "This page contains red flag keywords" : "This page does NOT contain red flag keywords";
}
popup.html
<!doctype html>
<html>
<head>
<title>RFchecker</title>
<script src="popup.js"></script>
</head>
<body style="background-color:#0F0;width:160px;height:90px;">
<div id="status">
<button id="getResults">Get Results</button>
<h4 id="results"></h4>
</div>
</body>
</html>
我希望看到的是网站上的任何地方都有Wikipedia单词:“此页面包含红旗关键字”,否则“此页面不包含红旗关键字”。
感谢您的帮助!