Skip to content Skip to sidebar Skip to footer

Chrome Extension: Create Tab Then Inject Content Script Into It

Upon receiving a message from a content script I want to create a new tab and fill the page it opens dynamically (for now I'm just trying to turn the newly created page red). event

Solution 1:

The problem is that you cannot inject scripts into chrome-extension://* pages (which your blankpage.html is).

For example, change

{url: chrome.extension.getURL("blankpage.html")} 

to

{url: "http://www.google.com"}

in your original codeblock and it will change the background to red. As far as I know there is no way around injecting into chrome-extension://* pages (I would assume the reason for this is that it is a giant security concern). I'm not sure what your extension is trying to do, but injecting into a "live" page should work...maybe you can create some API to generate a new "blankpage" on your server whenever the chrome.runtime.onMessage.addListener fires?

EDIT

So you can't inject stuff into chrome-extension://* pages, but you can pass messages to them and use some subset of chrome API's inside those new pages as mentioned below. So using message passing you will be able to do exactly what you want (modify the new page), albeit in a roundabout way. Here is a really simple proof of concept that works for me:

eventPage.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) 
  {
    chrome.tabs.create({url: chrome.extension.getURL("blankpage.html")}, turnTabRed);      
  });

functionturnTabRed(tab)
{
  chrome.tabs.sendMessage(tab.id, {"action" : "setBackground"});
}

blankpage.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if(request.action == "setBackground") document.body.style.background = "red";
  });

Post a Comment for "Chrome Extension: Create Tab Then Inject Content Script Into It"