background.js is not receiving chrome.runtime messages - google-chrome-extension

I have the following flow in my Google Chrome extension:
popupup.html runs popup.js (works fine):
<body>
<button id="copy">Get Data</button>
<script src="https://www.gstatic.com/firebasejs/7.2.2/firebase.js"></script>
<script src="popup.js"></script>
</body>
popup.js executes a basicData.js (works fine):
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("copy").addEventListener("click", startHandler);
});
function startHandler() {
chrome.tabs.executeScript({file: "basicData.js"}, function() {
});
}
basicData.js does some calculations etc and then sends a message to the background script:
...
console.log("Hello world"); //prints fine
chrome.runtime.sendMessage({...data});
background.js does not receive any message:
chrome.runtime.onMessage.addListener(function(response,sender,sendResponse) {
console.log("hiya")
if (response.type==="Data complete"){
console.log("Hello2");
chrome.tabs.sendMessage({...response});
}
})
Here is my manifest.json for reference:
{
"name": "Project X",
"version": "1.0",
"description": "Build an Extension!",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>","http://*/*", "https://*/*"],
"js": ["testScript.js"]
}
],
"browser_action": {
"default_popup": "popup.html"
},
"content_security_policy": "script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'; connect-src 'self' wss://*.firebaseio.com;",
"permissions": ["tabs","storage","declarativeContent", "activeTab","http://*/","https://*/","webNavigation"],
"manifest_version": 2
}
I copied most of this code and flow from a Google Chrome extension I made in the past which worked absolutely fine, so I am not sure why either basicData.js is not sending the message or background.js is not receiving it. All suggestions are appreciated.
Thanks for reading.

Related

Why is the background script not loading on Firefox add-on (works on Chrome)?

I'm developing a cross-browser extension which works in Chrome but not in Firefox - the background script is not loading.
I tried console.log in background.js and sending a message to the content script and logging message there.
background.js
browser.action.onClicked.addListener(async function (tab) {
console.log("clicked on extension icon");
browser.tabs.sendMessage(tab.id, { text: "toggle_overlay" })
});
js/content.js
...
browser.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log("message received", msg)
});
Content script works as expected on all code that's not depended on background.js
Folder structure
manifest.json (had to downgrade to v2 because Firefox doesn't support v3 yet)
{
"name": "Dev Mode",
"description": "Dev Mode",
"version": "0.0.1",
"manifest_version": 2,
"icons": {
"16": "./imgs/icon-16-dark.png",
"48": "./imgs/icon-48.png",
"128": "./imgs/icon-128.png"
},
"permissions": [
"activeTab",
"contextMenus",
"bookmarks",
"scripting",
"storage",
"<all_urls>"
],
"background": {
"scripts": ["background.js"],
"persistent": false // <-- also tried without, same result - background script doesn't lod
},
"browser_action": {
"default_icon": "./imgs/icon-16-dark.png",
"default_title": "Default Title"
},
"commands": {
"save-page": {
"suggested_key": {
"default": "Ctrl+Shift+S",
"mac": "Command+Shift+S"
},
"description": "some description"
}
},
"content_security_policy": "script-src 'self'; object-src 'self'; sandbox allow-scripts; script-src 'self' https://apis.google.com https://www.gstatic.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'",
"web_accessible_resources": [ "imgs/*.png", "overlay.html"],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"/js/content.js"
],
"run_at": "document_end",
"all_frames": false
}
]
}
I'm testing the Firefox extension with web-ext run to test the extension locally.
The correct API for this in Manifest v2 is browserAction instead of action that is only available in MV3.
So to fix it, in your background.js, switch to
browser.browserAction.onClicked.addListener
browser.action in Firefox is available in MV3. Your extension uses MV2 i.e. "manifest_version": 2,
Note: This API is available in Manifest V3 or higher.
Note: MV3 support is very limited in Firefox at the moment.

Google extension - message listener not working

this is a bit of my code that I have currently
Manifest
{
"name": "hidden",
"manifest_version": 2,
"content_security_policy": "script-src 'self'; object-src 'self'",
"permissions": [
"activeTab",
"storage"
],
"version": "hidden",
"icons": {hidden},
"description": "hidden",
"browser_action": {hidden},
"content_scripts": [
{
"matches": [hidden],
"run_at": "document_start",
"js": [ "injected.js", "content.js"]
}
],
"web_accessible_resources": ["injected.js"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
Injected.js
if (new RegExp(allowedUrls.join("|")).test(this._url))
{
console.log('test') <- I can see this message in console
chrome.runtime.sendMessage({interception: true});
}
Background.js
console.log("Atleast reached background.js") <- I can see that
chrome.runtime.onMessage.addListener(function (message, sender) {
console.log('inside listener') <- I cannot see that which means it doesn't get fired on message sent
if (message.interception) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {interception: true});
});
}
});
Can someone help me and tell me why it isn't working? My goal is to intercept XHR request in one file (injected.js), then receive that message on background.js and send that to another content.js file and do some stuff base on the response.

Chrome extension - How a sandboxed page access data from storage?

When user click the extension icon, it opens a sandboxed new page in new tab. From the page, I want to access data from storage. Didn't find any useful info from official doc, please enlighten me.
manifest.json
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "My extension"
},
"permissions": ["activeTab", "tabs", "storage", "<all_urls>"],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"sandbox": {
"pages": ["newtab.html"]
}
}
background.js
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.create({
url: chrome.extension.getURL("newtab.html"),
})
});
newtab.html
<html>
<head>
<script src="vue.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body
</html>
app.js
window.addEventListener('load', function () {
// access data from storage
})
The reason I'm using a sandbox page, is because Im using Vue.js which needs to use eval.

chrome.runtime.onMessage not receiving messages

I am trying to create my first extension where I want to send a message from contentScript to popup.js script but the message is not received.
background.js
chrome.runtime.onInstalled.addListener(function() {
chrome.webNavigation.onCompleted.addListener(function() {
chrome.browserAction.setPopup({popup: 'popup.html'});
chrome.tabs.executeScript({
file: 'contentScript.js'
});
}, {url: [{hostSuffix : 'domain.com'}]});
});
contentScript.js (here tried to put it outside of the load script but didn't help)
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.remove();
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
return true;
});
};
popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>HI</h1>
<section id='red'></section>
<script src="popup.js"></script>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("HEREEEE");
document.getElementById("red").innerHTML += "Hello";
}
);
Manifest
{
"name": "new extension",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["activeTab", "cookies", "sessions", "declarativeContent", "webNavigation", "http://*/*", "https://*/*"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"icons": {
"16": "images/get_started16.png",
},
"manifest_version": 2,
"web_accessible_resources": [
"script.js"
]
}
background.js is waiting for a page to be fully loaded, then execute contentScript and setPopup for browserAction popup.html - there is script for popup.js. The contentScript will execute another script and will send a message. The popup.js is listening for the message but it never arrive. Do you know why? Is it because of the background.js events?
My intention is to wait for certain page (can't use pageAction because it does not allow me to add badget) and then update the extension popup with appropriate content.

chrome API override history page examples

Am trying to override the history page in chrome using an extension. I have set the override page option in manifest.json file and created a new history.html file. The extension is running perfect and the history page showing blank now. I need to list all the history in my new override page history.html page. Is there any way to do this?
Here is my manifest.json file.
{
"name": "Recently visited urls",
"version": "1.0",
"description": "Recently visited urls",
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["popup.js"]
}],
"background": {
"scripts": ["jquery.js","background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Recently visited urls",
"default_popup": "popup.html",
"default_icon": "clock.png"
},
"permissions": [
"history",
"downloads"
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"chrome_url_overrides": {
"history": "history.html"
},
"manifest_version": 2
}
Thanks in advance!
If you mean why your customized history page is blank, have you declared history permission in your manifest.json?
Update:
Since chrome.history api can only be accessed through background scripts, we need to do message passing from background scripts to your override history page. However, we can't inject content scripts to chrome://history and after trying many methods, I think using localStorage is a workaround to solve this problem.
manifest.json
{
"name": "Search History",
"version": "1.0",
"manifest_version": 2,
"description": "Your description",
"chrome_url_overrides": {
"history": "history.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"history"
]
}
history.html (here I just concat all localStorage in a string, you can customize your view here)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p id="historyText"></p>
<script src="content.js"></script>
</body>
</html>
background.js (you can configure history items number by setting maxResults to other number)
chrome.browserAction.onClicked.addListener(function () {
chrome.history.search({ text: '', maxResults: 10 }, function (data) {
data.forEach(function(page) {
localStorage.setItem("Id: " + page.id + ", title: " + page.title, page.url);
});
});
});
content.js
var historyText = "";
for(var key in localStorage) {
historyText += key + ": " + localStorage.getItem(key) + ", ";
}
document.getElementById("historyText").innerText = historyText;

Resources