3

I am attempting to make a chrome extension that creates a new tab with a local 'blanksite.html' and injects some javascript code turning it green. Here's what I have so far.

background.js

chrome.browserAction.onClicked.addListener(function(activeTab){

  chrome.tabs.create({'url': chrome.extension.getURL("blanksite.html") }, function(tab) {
    chrome.tabs.executeScript(tab.id, {
      code: 'document.body.style.backgroundColor="green"'
    });
  });
});

manifest.json

{
  "manifest_version": 2,

  "name": "Open Green Google Tab",
  "description": "This extension opens a Green Google tab.",
  "version": "1.0",

  "background":{
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs",
    "activeTab"
  ]
}

This opens "blanksite.html" (literally an empty html file) in a new tab, but does not turn the tab green.

I've read the other answers at Chrome extension: create tab then inject content script into it, so I know why this doesn't work (not able to directly inject code into chrome://extension pages); but I wasn't able to make the solutions posted on the other answers work for me. Is there a clear, full piece of small code that can make what I want to do work?

I'm afraid I do not understand messaging very well, so for any solution that has that as a piece, a more comprehensive explanation would be greatly appreciated.

Community
  • 1
  • 1
Timothy Chu
  • 153
  • 1
  • 9

1 Answers1

1

Not sure why starting message passing from background page to blanksite.html won't succeed (maybe it's too late to listen to message in blanksite.html when it's created?).

However, starting message passing from blanksite.html and executing corresponding action in the response work well, see following sample code:

blanksite.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script src="blanksite.js"></script>
</body>
</html>

blanksite.js

chrome.runtime.sendMessage({src: "newtab"}, function(response) {
    if(response.action === 'changeColor') {
        document.body.style.backgroundColor = 'green';
    }
});

background.js

chrome.browserAction.onClicked.addListener(function(activeTab) {
    chrome.tabs.create({url: chrome.runtime.getURL('newtab.html')});
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.src === 'blanksite') {
        sendResponse({action: 'changeColor'});
    }
});
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47