Injecting Javascript Into Newly Created Tab In Chrome Extension
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. backgr
Solution 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'});
}
});
Post a Comment for "Injecting Javascript Into Newly Created Tab In Chrome Extension"