Injecting Javascript into Newly Created Tab in Chrome Extension

本秂侑毒 提交于 2019-12-20 04:58:12

问题


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.


回答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'});
    }
});


来源:https://stackoverflow.com/questions/38057056/injecting-javascript-into-newly-created-tab-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!