[英]How to have more than one instruction in this Chrome Extension code?
i'm reading Chrome Extension Docs and i'm trying to make a button changes a ID display to none.我正在阅读 Chrome 扩展文档,我正在尝试通过按钮将 ID 显示更改为无。
This is what i have done so far:这是我到目前为止所做的:
changeColor.onclick = function(element) {
let color = element.target.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
{code: 'document.getElementById("topnav").style.display = "none";'});
});
};
I was trying to put a toggle, so when the button is clicked, the display comes back to block but i wanst able.我试图设置一个切换按钮,所以当点击按钮时,显示会恢复阻塞,但我希望能够。
This is what i tried:这是我试过的:
changeColor.onclick = function(element) {
let color = element.target.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,tabs[1].id,
{code: 'document.getElementById("topnav").style.display = "none";'},
{code: 'document.getElementById("topnav").style.display = "block";'});
});
};
Also tried this solution:也试过这个解决方案:
changeColor.onclick = function(element) {
let color = element.target.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
});
};
I was able to make it work outside chrome.tabs.executeScript but i need it inside, so it changes the css of the page i choose.我能够让它在 chrome.tabs.executeScript 之外工作,但我需要它在里面,所以它改变了我选择的页面的 css。
It probably has usesless codes for what i'm trying to do.对于我正在尝试做的事情,它可能有无用的代码。
The reason is because i just followed https://developer.chrome.com/extensions/getstarted原因是因为我刚刚关注了https://developer.chrome.com/extensions/getstarted
Many thanks!非常感谢!
'code' object takes in a string, simply separate them with semicolons if you have multiple instructions, for example: 'code' 对象接受一个字符串,如果您有多个指令,只需用分号分隔它们,例如:
chrome.tabs.executeScript(tabs[0].id, {
code: "alert('first alert');alert('second alert')";
});
For the toggle effect, you could try this对于切换效果,你可以试试这个
chrome.tabs.executeScript(tab[0].id, {
code: `document.getElementById('topnav').style.display = document.getElementById('topnav').style.display === 'none'
? 'block'
: 'none'`;
});
You can make your script a bit more useful by using an if...else
statement.您可以通过使用
if...else
语句使您的脚本更有用。 You can read more about it here .您可以在此处阅读更多相关信息。
In your case I would do something like:在你的情况下,我会做这样的事情:
const topnav = document.getElementById("topnav");
if (topnav.style.display === 'block') {
topnav.style.display = 'none';
} else {
topnav.style.display = 'block';
}
This way, if the element is display: block
, you set it to display: none
, and vice-versa.这样,如果元素是
display: block
,则将其设置为display: none
,反之亦然。 Good luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.