为什么 window.open() 和 window.close() 在 Extension 中不起作用?



好的,所以我目前正在尝试通过chrome扩展程序自动化一些任务。这是我的所有文件,问题出在我的内容上.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>

弹出窗口.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 的新选项卡,然后等待一段时间并自动关闭该选项卡。出于某种原因,窗口.关闭((;方法在做任何事情时,谷歌打开,然后保持打开状态。有什么想法吗?

因此,我看到两件事会对您有所帮助。

  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);

最新更新