我想我已经在SO上阅读了这个问题的所有现有答案,但无法解决我的问题,所以这里是:
想法是在单击扩展图标时显示的弹出窗口中单击按钮时,在当前选项卡上通过id删除div元素。
这是我的代码:
popup.html
<!doctype html>
<html>
<head>
<title>TurboViewer</title>
<script src="popup.js"></script>
<script src="contentscript.js"></script>
</head>
<body>
<h3>Turbo Viewer</h3>
<button id="checkPage">Check this page now!</button>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendMessage(tab.id, {action: "getDOM"}, function(response) {
console.log("We are good");
});
});
}, false);
}, false);
contentscript.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action == "getDOM"){
var sbElement = document.querySelector('div#sidebar');
sbElement.parentElement.removeChild(sbElement);
sendResponse({dom: "Successfully removed"});
}
else
sendResponse({}); // Send nothing..
});
最后 manifest.json
{
"manifest_version": 2,
"name": "TurboView Plugin",
"description": "This extension will modify your view of the webpage",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"matches": ["*://*.example.com/*"],
"js": ["contentscript.js"]
}
]
}
我注意到的第一件事是我在contentscript.js中的断点永远不会被击中。
所以我不确定它是否会被加载。
任何想法都赞赏, 感谢