Jus*_*aat 1 google-chrome google-chrome-extension
我正在尝试制作一个 Chrome 扩展程序,该扩展程序在用户打开新标签时运行脚本。
我有以下基本代码,只要单击扩展按钮,它就会将页面涂成红色。
当我导航到实际网站时,它似乎工作正常(例如:在 stackoverflow.com 上,单击我的扩展程序图标,页面变为红色)。但是,如果我只是创建一个全新的选项卡并单击按钮,则会加载弹出窗口但页面永远不会改变颜色。
清单.json:
{
"manifest_version": 2,
"name": "ConsoleTap",
"version": "0.1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "menu.html"
},
"permissions": [
"tabs",
"<all_urls>",
"https://ajax.googleapis.com/"
]
}
Run Code Online (Sandbox Code Playgroud)
菜单.html:
<!doctype html>
<html>
<head>
<script src="menu.js"></script>
</head>
<body>
hello
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
菜单.js:
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
});
Run Code Online (Sandbox Code Playgroud)
关于为什么页面不会更新新选项卡上的背景颜色的任何想法?我猜DOMContentLoaded它永远不会被解雇,或者它在以某种方式发生负载后正在监听?
In Chrome 60 and older it was still possible to inject content scripts into the child frames of the default new tab page because it consists of several frames so the restriction only applies to the top level frame. For the default newtab (not some newtab extension) we can match its frame url (https://www.google.com/_/chrome/newtab*) to inject a content script which will activate once a message from the popup is received:
manifest.json:
{
"name": "executeScript",
"version": "1.0",
"content_scripts": [{
"matches": ["https://www.google.com/_/chrome/newtab*"],
"js": ["newtabcontent.js"],
"run_at": "document_start"
}],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)newtabcontent.js:
chrome.runtime.onMessage.addListener(function(msg) {
if (msg == "activate") {
document.body.style.background = 'red';
document.body.style.backgroundColor = 'red';
}
});
Run Code Online (Sandbox Code Playgroud)popup.js:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (tabs[0].url == "chrome://newtab/") {
chrome.tabs.sendMessage(tabs[0].id, "activate");
} else {
chrome.tabs.executeScript({
code: "document.body.style.backgroundColor='red'",
allFrames: true
});
}
});
Run Code Online (Sandbox Code Playgroud)Notes:
chrome.tabs.executeScript can't be used on newtab page because it instantly fails for the main frame due to unsupported scheme chrome:// and doesn't even proceed to execute on child frames.| 归档时间: |
|
| 查看次数: |
2579 次 |
| 最近记录: |