gpt4 book ai didi

javascript - 为什么 window.open() 和 window.close() 在扩展中不起作用?

转载 作者:行者123 更新时间:2023-11-28 03:27:36 25 4
gpt4 key购买 nike

好吧,我目前正在尝试通过 chrome 扩展程序自动执行一些任务。这是我的所有文件,问题出在我的 content.js 上:

manifest.json:

{
"manifest_version": 2,

"name": "Click to execute",
"description": "Execute script after click in popup.html (chrome extension) http://stackoverflow.com/questions/20764517/execute-script-after-click-in-popup-html-chrome-extension.",
"version": "1.0",

"icons": {
"48": "icon.png"
},

"permissions": [
"tabs", "<all_urls>"
],

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}

弹出.html:

<!DOCTYPE html>
<html>
<body style="width: 300px">
Open <a href="http://stackoverflow.com" target="_blank">this page</a> and then
<button id="clickme">click me</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js:

function hello() {
chrome.tabs.executeScript({
file: 'content.js'
});
}

document.getElementById('clickme').addEventListener('click', hello);

内容.js:

let firstCl = function(){
document.getElementsByClassName('nav-link')[6].click();
};

let openWin = function(){
window.open('www.google.com');
};

let closeWin = function(){
window.close()
}


setTimeout(firstCl, 3000);
setTimeout(openWin, 6000);
setTimeout(closeWin, 9000);

我尝试点击一个链接,然后使用 google.com 打开一个新标签,然后等待一段时间并自动关闭该标签。由于某种原因 window.close();方法 inst 做任何事情,谷歌都会打开,然后就保持打开状态。有什么想法吗?

最佳答案

我看到的两件事可以帮助你。

  1. 如果您想打开新选项卡,则需要添加'_blank',否则它将接管当前窗口。所以 window.open('www.google.com', '_blank');

  2. 您需要引用您打开的窗口。因此,将其分配给一个变量,然后关闭生成的特定窗口

let theWindow;

let firstCl = function() {
document.getElementsByClassName('nav-link')[6].click();
};

let openWin = function() {
theWindow = window.open('www.google.com', '_blank');
};

let closeWin = function() {
theWindow.close()
}

setTimeout(firstCl, 3000);
setTimeout(openWin, 6000);
setTimeout(closeWin, 9000);

关于javascript - 为什么 window.open() 和 window.close() 在扩展中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com