Chrome插件Content Scripts关闭当前页的方法

在制作Chrome插件的过程中,我使用Content Scripts注入到当前页中,想实现当点击页面的按钮后关闭当前页面(tab)。

习惯性调用:window.close(),结果报错:Scripts may close only the windows that were opened by it

好吧,google之,网友提供了以下方法:

  window.opener = null;
  window.open('','_self');
  window.close();

经尝试依然报错无效,就算使用了所谓的hack,即

  window.open(' ','_self');

加多了一个空格之后,发现页面也是刷新了一下(可能的关闭又再打开)。

最后在http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome看到讨论,大概意思是Chrome的新版本加强了安全性和谐了hack云云。

然后有人建议使用Chrome的API。

查阅了文档后,尝试直接在Content Scripts调用chrome.tabs.remove(id)来移除,结果报错说找不到该函数。

继续查阅文档后发现Content Scripts是没有权限调用这个的,但是可以通过sendMessage来发送消息给background.js(插件后台)。

于是采用以下方法:

  // Content Scripts中
  $("#quit_button").click(function() {
  chrome.extension.sendMessage({greeting: "close_tab"});
  });
   
  // background.js中
  chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("Request comes from content script " + sender.tab.id);
  if (request.greeting === "close_tab"){
  chrome.tabs.remove(sender.tab.id);
  }
  });

先在background.js中注册消息处理函数,当点击按钮时,Content Scripts向插件后台发送消息,该消息触发其调用chrome.tabs.remove(id)来关闭该页面。

这样就间接实现了预期目标。

猜你喜欢

转载自www.cnblogs.com/simadi/p/12404472.html