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

标签 javascript google-chrome-extension

好吧,我目前正在尝试通过 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/

相关文章:

javascript - 检测Flash播放器当前是否正在播放? - Chrome 扩展

javascript - 如何使用 Gmails 内置的方法发送 Gmail 谈话消息

javascript - 如何在 chrome 扩展中自动更新 javascript

php - 如何使用javascript模拟点击href为php的链接

javascript - Uncaught TypeError : $(. ..).tooltip 不是 Laravel 应用程序中的函数(Bootstrap 4 预设)

javascript - Bluebird Promisify execFile 无法得到解决的 promise

javascript - jQuery RTE 建议

javascript - 如何在浏览器的新标签页 (_blank) 中设置打开 pdf 文件的标题

javascript - 检查本地存储中是否具有相同的值

javascript - Chrome 扩展替换当前文本区域中的单词