I have a chrome extension that I built that leaks memory. I am working on fixing the memory leak, but in the mean time a few friends are already using it.
As a temporary measure I want to include a patch which would restart the extension automatically, periodically.
How to do this?, namely restart a chrome extension from within the extension itself.
thanks,
You can have two extensions. And restart the target extension from the other. If that suits you read on.
content.js
window.addEventListener('load', function (e) {
// create a button and add it to the page
var btn = document.createElement('button');
btn.innerHTML = 'Restart child extension';
btn.addEventListener('click', function (e) {
// on button click send message to the background script
chrome.extension.sendMessage({restart: true}, function (res) {
console.log(res);
});
}, false);
var body = document.querySelector('body');
body.appendChild(btn);
}, false);
background.js
// first get your target (child) extension by it's name
var child = null;
chrome.management.getAll(function (info) {
for (var i=0; i < info.length; i++) {
if (info[i].name == 'Test child extension') {
child = info[i];
break;
}
}
});
function disable (cb) {
chrome.management.setEnabled(child.id, false, cb);
}
function enable (cb) {
chrome.management.setEnabled(child.id, true, cb);
}
function afterEnable () {
// notify the content script
resRestart({restarted: true});
}
var resRestart = null;
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
// if we receive request with restart variable, save a reference to the
// sendResponse function and disable the child extension
switch (true) {
case request.restart: resRestart = sendResponse; disable(); break;
}
return true;
});
chrome.management.onDisabled.addListener(function (extension) {
// this one is fired when extension is restarted
// check if this is our child extension and re-enable it
if (extension.name == 'Test child extension') {
enable(afterEnable);
}
});
manifest.json (parent)
{
"manifest_version": 2,
"name" : "Test parent extension",
"version" : "1.0",
"description" : "Whatever",
"background" : {
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"*://localhost/*"
],
"js": [
"content.js"
],
"run_at": "document_end",
"all_frames": true
}
],
"permissions": [
"tabs",
"management",
"*://localhost/*"
]
}
manifest.json (child)
{
"manifest_version": 2,
"name" : "Test child extension",
"version" : "1.0",
"description" : "Whatever",
"content_scripts": [
{
"matches": [
"*://localhost/*"
],
"css": [
"style.css"
],
"run_at": "document_end",
"all_frames": true
}
]
}
directory structure
.
├── background.js
├── child
│ ├── manifest.json
│ └── style.css
├── content.js
└── manifest.json
Now open up about:extensions and http://localhost in split screen. Click on the button and see how the child extension is refreshed each time. Also you can check out the console. Even try to disable the child extension from within about:extensions - it's not possible as long as the parent extension is running.
Related
I have created a Chrome extension that queries for elements on some webpages that feature dynamic content loading via AJAX; -- when on some of these webpages, my content.js script triggers too early (prior to the loading of the elements I need).
As a result, I set up a listener in my background script to listen for when the page has loaded enough of the elements and then it re-injects the content.js script.
background.js:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.type == "hats_men") {
chrome.windows.get(sender.tab.windowId, function () {
/*get user's size based on product type (ie. hat)*/
var res = findSize();
if (res == -1) {
/*do nothing since no size exists for them*/
}
else {
/*send size back to content script via messaging*/
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { type: "res_size", size: res });
});
}
});
}
});
var oldTab;
chrome.tabs.onUpdated.addListener(
function (tabId, changeInfo, tab) {
var temp = tab.url;
/*IF: on a product page, execute script.*/
if (temp && (temp.indexOf("shop.com/shop/") > -1)) && (changeInfo.url === undefined) && (temp != oldTab)) {
chrome.tabs.executeScript(tabId, { file: "content.js" });
oldTab = tab.url;
}
});
Unfortunately, I am unable to call any functions from content.js that exist in my other js files. Is there a way to invoke them? For context, I've included the js files in question into "web_accessible_resources" and "content_scripts" in my manifest.json.
external.js:
function monk(x) {
if (x != 0) {
console.log(x);
}
}
content.js:
/*get current url*/
var cur_url = window.location.href;
/*check if user is on supported site*/
if (cur_url.indexOf("hello.com/shop/") > -1 && cur_url.indexOf("quantity=1") > -1) {
/*get relevant user data*/
chrome.storage.sync.get({ data: [] }, async function (user) {
/*call prod_res() to get item details from dynamically loaded product page*/
const res = await prod_res();
/*if the product is for men*/
if (res[1] == "man") {
/*if the product is a hat*/
if (res[0] == "hat") {
/*send message to background script that this is a mens' hat*/
chrome.runtime.sendMessage({ type: "hats_men" },
function (response) {
/*listen for user's hat size in the request/message from background script*/
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
/*log user's hat size to console*/
if(request.type == "res_size"){
monk(request.size][1]);
}
}
});
}
);
}
}
});
}
/nothing logs to console/
manifest.json:
{
"manifest_version": 2,
"name": "E-Co",
"version": "0.2",
"background": {
"scripts": [ "jquery-3.5.1.min.js", "reduce.js", "background.js" ],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"jquery-3.5.1.min.js",
"content.js",
"external.js"
]
}
],
"web_accessible_resources": [
"external.js"
],
"browser_action": {
"default_icon": "logo_active.png",
"default_popup": "popup.html",
"default_title": "E-co Pop-Up"
},
"icons": {
"16": "icon_16.png",
"48": "icon_48.png",
"128": "icon_128.png"
},
"permissions": [
"storage",
"notifications",
"tabs",
"*://*/*"
],
"content_security_policy": "script-src 'self' https://ajax.aspnetcdn.com; object-src 'self'"
}
Your content.js sends a message and uses a callback to wait for a response, which must be sent back by using sendResponse. Your background script doesn't send a response, it only sends a new message, so the first callback never runs.
Use the simple messaging example from the documentation:
content.js
chrome.runtime.sendMessage({type: 'hats_men'}, monk);
background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type == 'hats_men') {
sendResponse(findSize());
}
});
Note that sendResponse must be called for each message that was sent with a callback like we did above, otherwise you'll see errors in the console (unless you suppress them).
I am making a chrome extension in which I want to change the color of the "Send" button of Compose dialog.
What is the best way to do it?
Thanks in advance!
Update-
Here is the function of content.js I am currently using to change the color-
function modifySendButton(check, form) {
var send_button = $(form).siblings('table').find('div[role="button"][aria-label="Send (Ctrl-Enter)"]');
if (0 === send_button.length) {
send_button = $(this).siblings('table').find('div[role="button"][aria-label="Send (⌘Enter)"]');
}
if (true === check) {
send_button.addClass("active-send-button");
} else {
send_button.removeClass("active-send-button");
}
}
It is changing the Send button color, but I want to know is it the right way to do so?
You can try to use mutation observer inside the content-script.
Complete example:
manifest.json
{
"manifest_version": 2,
"name": "Btn Color",
"description": "",
"version": "1.0.0",
"content_scripts": [{
"js": ["content-script.js"],
"matches": [
"https://mail.google.com/*"
],
"run_at": "document_end"
}],
"permissions": [
"tabs"
]
}
content-script.js
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes && mutation.addedNodes.length) {
// look for the button
const sendBtn = document.querySelector('.dw [aria-label*="Send"]');
if(sendBtn) {
sendBtn.style.background = 'red'; // set your styles
}
}
});
});
var targetNode = document.body;
observer.observe(targetNode, {childList: true});
So I'm trying my hand at a google chrome extension which in theory should be extremely straight forward. I know there are tons of stack queries and I've tried a few, I've even copied and pasted direct solutions for testing and I have been unsuccessful. So here is the project. When a page loads, check the html content, and change the icon programmatically.
This is my content.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
var markup = document.documentElement.innerHTML;
var m = markup.indexOf("candy");
if (m > -1) {
chrome.browserAction.setIcon({path: "check.png"});
} else {
chrome.browserAction.setIcon({path: "cross.png"});
}
}
})
This is my manifest.json
{
"manifest_version": 2,
"name": "Tag Analyzer Plugin",
"description": "Check if tag exist on page",
"version": "1.0",
"browser_action": {
"default_icon": "cross.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"permissions": ["<all_urls>"]
}
Right now I'm running this item as a content script because as a content script I can use the logic
var markup = document.documentElement.innerHTML;
var m = markup.indexOf("candy");
if (m > -1) {} else {}
However as a content script the chrome API stuff doesn't work. When I run this script as a background script the script works, except that
var markup = document.documentElement.innerHTML;
doesn't return the pages html, it returns the injected script html.
I've read this stack which was informative as to what the difference was and I've read and tested many stacks like here this, without much success. So obviously i'm missing something and doing something wrong. Thank in advanced for any help.
UPDATES:
So I've made some modifications, but it's still not working, though I think that it's closer to working.
As per the comments below I am now using a content script and background script. No errors are being thrown, however the background script isn't doesn't anything.
content.js
var markup = document.documentElement.innerHTML;
var m = markup.indexOf("candy");
if (m > -1) {
chrome.runtime.sendMessage({"found" : true});
} else {
chrome.runtime.sendMessage({"found": false});
}
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if request.found {
alert("HERE");
chrome.browserAction.setIcon({
path: "check.png",
tabId: sender.tab.id
});
} else {
alert("HERE2");
chrome.browserAction.setIcon({
path: "cross.png",
tabId: sender.tab.id
});
}
});
manifest.json
{
"manifest_version": 2,
"name": "Tag Analyzer Plugin",
"description": "find tag on page",
"version": "1.0",
"browser_action": {
"default_icon": "cross.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"permissions": ["<all_urls>"]
}
I've added some alerts on the background.js to see if it was being trigger and nothing, not does the icon change.
I'm building an google extension that inserts html in page and shows a menu on browser action icon click and I don't find way to keep my extension open when I reload the page. So on every reload, we have to active it again from Browser Action icon.
Below the manifest file
{
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": "img/icone.png",
"default_title": "show menu"
},
"icons" : {
"128" : "img/icone_128.png",
"48" : "img/icone_48.png",
"32" : "img/icone_32.png",
"24" : "img/icone_24.png",
"16" : "img/icone_16.png"
},
"manifest_version": 2,
"name": "p|layer",
"version": "1.0.4",
"content_scripts": [
{
"matches": [ "<all_urls>"],
"css":["css/grid.css", "css/font-awesome.min.css"],
"js":["js/jquery-1.11.1.min.js","js/jquery-ui.js", "js/jquery.nicefileinput.min.js"]
}
],
"web_accessible_resources": [
"fonts/fontawesome-webfont.woff"
],
"permissions": [ "activeTab"]
}
script (background.js) injecting contentscript
chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON
chrome.tabs.executeScript(tab.id,
{"file": "js/contentscript.js"},
function () { // Execute your code
console.log("Script Executed .. "); // Notification on Completion
});
chrome.tabs.insertCSS(tab.id, {file: "css/grid.css"});
chrome.tabs.insertCSS(tab.id, {file: "css/font-awesome.min.css"});
chrome.tabs.insertCSS(tab.id, {file: "css/slider.css"});
});
any help will be appreciated
So, from the comments the problem was inferred: your button click activates your content script, but a page reload clears it. Assuming you want the button click to act as a toggle:
1) Always inject the content script / CSS, but don't show the UI immediately:
"content_scripts": [
{
"matches": [ "<all_urls>"],
"css": ["css/grid.css", "css/font-awesome.min.css", "css/slider.css"],
"js": [
"js/jquery-1.11.1.min.js", "js/jquery-ui.js",
"js/jquery.nicefileinput.min.js", "js/contentscript.js"
]
}
],
2) Keep track of "activated" tabs:
var activeTabs = {};
chrome.browserAction.onClicked.addListener( function(tab){
var active;
if(activeTabs[tab.id]){
delete activeTabs[tab.id];
active = false;
} else {
activeTabs[tab.id] = true;
active = true;
}
/* (part 3) */
});
chrome.tabs.onRemoved.addListener( function(tabId){
delete activeTabs[tabId];
});
chrome.tabs.onReplaced.addListener( function(newTabId, oldTabId){
if(activeTabs[oldTabId]) activeTabs[newTabId] = true;
delete activeTabs[oldTabId];
});
3) Use messaging to show/hide UI:
Content script:
chrome.runtime.onMessage.addListener( function(message. sender, sendResponse){
if(message.showUI) showUI();
if(message.hideUI) hideUI();
});
Background script:
chrome.browserAction.onClicked.addListener( function (tab) {
var active;
/* (part 2) */
if(active) {
chrome.tabs.sendMessage(tab.id, {showUI: true});
} else {
chrome.tabs.sendMessage(tab.id, {hideUI: true});
}
});
Additional robustness can be added for the cases of extension reload, but that's the gist of it.
I am trying to develop a Chrome extension to open Office documents stored in Confluence in a new tab using the IE Tab extension.
In the 'View Page Attachment' screen, there is an 'Edit in Office' link for Office file attachments. The link has a click event that creates a new instance of a URLLauncher, which is used to open the document. This feature is not supported in Chrome, so I want to add my own URLLauncher prototype into the web page to make it work.
In short, this is my idea:
Create a Chrome extension with a content script that injects a URLLauncher prototype into the 'View Page Attachment' page (I don't know if this is the right approach, so I am open to suggestions).
When the user clicks on the 'Edit in Office' link, the URLLauncher.open method opens the file attachment in a new tab by calling the IE Tab extension.
I can see the 'Hi there!' alert every time I load a web page, and that confirms that content.js is being injected. Nevertheless, the URLLauncher is not available in the web page. I think this is because the global window object of the content script is distinct from the page/extension's global namespace (i.e., window.URLLauncher is undefined). How could I reorganize my code to overcome this obstacle?
These are my files:
manifest.json
{
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
]
},
"content_scripts": [ {
"js": [ "content.js" ],
"matches": [ "<all_urls>" ]
} ],
"description": "This is a test extension",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"name": "Test extension",
"version": "1.0.0"
}
background.js
chrome.tabs.executeScript(null, {
code: "document.body.appendChild(document.createElement('script')).src='" +
chrome.extension.getURL("content.js") + "';"
}, null);
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.id == "doUrlLaunch") {
chrome.tabs.create({ url: request.nUrl, selected: true });
sendResponse({result: "goodbye"});
}
}
);
content.js
var prefixUrl = 'chrome-extension://hehijbfgiekmjfkfjpbkbammjbdenadd/iecontainer.html#url=';
alert('Hi there!');
function URLLauncher() {
}
URLLauncher.prototype = {
open : function(urlStr) {
var newUrl = prefixUrl + 'https://host.com' + encodeURI(urlStr);
chrome.runtime.sendMessage({id: "doUrlLaunch", nUrl: newUrl}, function(response) {
});
}
}
Thanks in advance.
UPDATE 1
I edited the files following the instructions given by Rob W and this page ('Message Passing'); now the code is injected in the page itself, but a major problem still remains. The actual JS code sends a message to the content script, but the message is not caught by the listener, so the new tab is not created and the callback function does not receive a response; the error message I got: Error in event handler for (unknown): TypeError: Cannot read property 'success' of undefined.
These are the updated files:
manifest.json
{
"manifest_version": 2,
"content_scripts": [ {
"js": [ "content.js" ],
"matches": [ "<all_urls>" ]
} ],
"web_accessible_resources": [ "script.js" ],
"description": "This is a test extension",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"name": "Test extension",
"version": "1.0.0",
"externally_connectable": {
"ids": ["*"],
"matches": ["*://*.hostname.com/*"]
}
}
content.js
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
chrome.runtime.onMessage.addListener(
//Unreachable code!
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.id == "doUrlLaunch") {
chrome.tabs.create({ url: request.nUrl, selected: true });
sendResponse({result: "goodbye"});
}
}
);
script.js
var prefixUrl = 'chrome-extension://hehijbfgiekmjfkfjpbkbammjbdenadd/iecontainer.html#url=';
function URLLauncher() {
}
URLLauncher.prototype = {
open : function(urlStr) {
var newUrl = prefixUrl + 'https://hostname.com' + encodeURI(urlStr);
chrome.runtime.sendMessage({id: "doUrlLaunch", nUrl: newUrl}, function(response) {
if (!response.success)
console.log('Something went wrong...');
});
}
}
Not sure if you're still interested in an answer, but in your edited files your problem is where your listener sits.
chrome.runtime.sendMessage does not reach content scripts; it is intended for extension pages. Message passing to content scripts works through chrome.tabs.sendMessage, but this is irrelevant for this task.
Content scripts can't call chrome.tabs as they do not have the required API access.
A solution would be to call a background script, that can receive those messages and can call the required API.
Therefore, you need a third script, taking out this code from content.js:
// background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.id == "doUrlLaunch") {
chrome.tabs.create({ url: request.nUrl, selected: true });
sendResponse({result: "goodbye"});
}
}
);
And modify your manifest:
"background": { "scripts": [ "background.js" ] },