Content Scripts Chrome plug-in method to close the current page

In the process of making Chrome plugin, I use Content Scripts injected into the current page, click on the button want to achieve when the page closes the current page (tab).

Habitual call: window.close (), the results being given: Scripts may close only the windows that were opened by it.

Well, google it, users provides the following methods:

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

Error by trying to remain valid, even if the use of the so-called hack, that is,

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

After adding in a box and I found the page is refreshed a bit (possibly closed again open).

Finally http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome see discussion about the meaning of the new version of Chrome strengthened security harmony hack and so on.

Then it was suggested to use the Chrome API.

After a review of the documentation, try to direct the Content Scripts call chrome.tabs.remove(id)to remove results that can not find the error function.

After continuing consult the documentation is found to Content Scripts do not have permission to call this, but you can send a message by sendMessage to background.js (plug-in the background).

Then the following method:

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

First registration message handler in background.js, when the button is clicked, Content Scripts send a message to plug the background, the message triggers its call chrome.tabs.remove(id)to close the page.

This indirectly to achieve the desired objectives.

Guess you like

Origin www.cnblogs.com/simadi/p/12404472.html