chrome.runtime.onMessage not receiving messages - google-chrome-extension

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.

Related

How to change BadgeText from background script

Total newbie here.
I'm trying to create a very simple chrome extension. Its main functionality is to change its BadgeText depending on some API endpoint response. I want to check the endpoint every 5 seconds so I want to run it in the background. Here is what I've got:
manifest.json:
{
"manifest_version": 2,
"name": "BusyIndicator",
"description": "busy indicator",
"version": "1.0",
"background": ["background.js"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": []
}
popup.html:
<!doctype html>
<html>
<head>
<title>BusyIndicator</title>
<script src="popup.js"></script>
</head>
<body>
<h3>nothing here yet</h3>
</body>
</html>
popup.js is just an empty file right now
background.js:
setInterval(function() {
fetch('https://toiletbusy.herokuapp.com/')
.then(function(response) {
if (response.json.busy == false) {
chrome.browserAction.setBadgeText({text: 'BUSY'});
} else {
chrome.browserAction.setBadgeText({text: 'FREE'});
};
});
}, 5000);
I tried different things but it looks like background.js is not getting executed at all (e.g. console.log does not log anything)

Chrome Extension Developement : How to read the data from webpage and display it on popup.html?

So I was working on basic example and here is my requirement for chrome extension : The extension should be able to read the data from webpage and display it on the popup when icon clicked upon.
I have these files - manifest.json , popup.html , background.js , content.js , webPage.html (this is html file stored at my local machine and data is to be read from this page)
manifest.json
{
"name": "Test",
"version": "1.0",
"description": "Testing",
"permissions": ["file:///A:/Study/TestExt/webp.html"],
"content_scripts": [
{
"matches": ["file:///A:/Study/TestExt/webp.html"],
"js": ["content.js"]
}
],
"background": {
"persistent": true,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Test",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
popup.html
<html>
<head>
<script src= "background.js"></script>
</head>
<body>
<p id="writeWord"></p>
</body>
</html>
webp.html
<html>
<body>
<div >
<p id="readWord">WordToBeRead</p>
</div>
</body>
</html>
content.js
var innerText = document.getElementById("readWord").innerHTML;
var k = new Object();
k.textWord = innerText;
chrome.runtime.sendMessage(k, function(response) {
console.log("hello");
});
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.textWord == "WordToBeRead")
document.getElementById("writeWord").innerHTML = request.textWord;
});
So ideally when I click on extension icon I should get popup with word "WordToBeRead" but I am getting only empty popup. I can't figure it out where exactly I am going wrong.

I am unable to make 2 way communication between content script and popup

I am unable to make 2 way communication between content script and popup.
I could make a communication with content script and hence alert "Message received is showing up"
But feedback alert "response received" is not showing up. But the "response received" alert is showing when I inspect popup and then click on the button.
My question is that why would I need to inspect popup to get feedback alert "response received"? How can I get response without inspecting popup?
Popup HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Manifest json
{
"manifest_version": 2,
"name": "Such Activity",
"description": "Wow",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/",
"<all_urls>"
],
"content_scripts": [
{
"matches": [ "https://*/*", "http://*/*" ],
"js": [ "jquery.js", "content_script.js" ]
}
]
}
Popup HTML
<!doctype html>
<html>
<head>
<title>activity</title>
<script src="jquery.js"></script>
</head>
<body>
<button id="clickactivity">click</button>
<script src="popup.js"></script>
</body>
</html>
Popup JS
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { sender: "Hi" }, function (response) {
if (response.receiver == "Hello") {
alert("Response recieved");
}
});
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript);
Content script JS
$(document).ready(function () {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.sender == "Hi") {
alert("Message Received");
sendResponse({ receiver: "Hello" });
}
});
});

send data from popup to content script after button click

I am making a chrome extension where I want to take user input in the popup and fill the textbox of a page. I have the following code but the data from the popup does not reach the content script.
Manifest.json
{
"manifest_version": 2,
"name": "Copy from popup to current tab",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"storage"
],
"content_scripts": [{
"js": ["content.js"],
"matches": ["*://*/*"],
"run_at": "document_end"
}]
}
Popup.html
<!DOCTYPE html>
<html>
<head>
<title>Copy from popup to webpage</title>
<script src="popup.js"></script>
</head>
<body>
<input type= "text" id = "inp" height='50' width = '200'></input>
<button id="send">Click Me</button>
</body>
</html>
Popup.js
window.onload = function(){
document.getElementById('send').onclick=LogIn;
}
function LogIn(){
var data = document.getElementById('inp').value;
chrome.storage.local.set({
data : data
},function(){
chrome.tabs.executeScript({
file: "content.js"
});
}
);
}
Content.js
chrome.storage.local.get('data',function(items){
var gotdata = items.data;
chrome.storage.local.remove('data');
});

Display Specific Line Of Source Code in Popup

I'm very much new to the whole chrome extensions world.
I've read through the tutorial "hello world" pages and tried to gain an understanding of content_scripts and background.html - but I may have overdosed and can't seem to find an answer to something I'm sure is a simple task.
In a tab a site contains the following Hidden HTML:
<div class="XYZ">
<input id="form_ID" type="hidden" value="REF_CODE#Product_CODE#Product Name#">
</div>
What I'm trying to figure out is how I can Display the
RefCode
ProductCode
Product Name
In a popup.html
I'm not looking at editing the html or manipulating it in any way.. it is strictly just displaying the hidden HTML - in an easy to read Popup.
Hope that makes sense..
Thanks in Advance.
UPDATE:
Popup.html
<html>
<head>
<script>
function readIds() {
console.log('Send request to content script');
document.getElementById("response").innerText = "Requesting...";
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id, {cmd: "readIds"}, function(response){
console.log('Response from page is:' + response);
document.getElementById("response").innerText = JSON.stringify(response);
});
});
}
</script>
</head>
<body style="width:400px;">
Click to read ids
<pre id="response"></pre>
</body>
</html>
Content_script.js
// add a listener to get messages from background, popup
chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
switch (request.cmd) {
case "readIds":
console.log("readIds", request);
document.getElementById("productID");
sendResponse({refCode:1, productCode: 2, productName: 3});
break;
}
});
manifest.json
{
// Required
"name": "WP Debug",
"version": "0.0.1",
// Recommended
"description": "A plain text description",
"icons": { "48": "icon.png" },
//"default_locale": "en",
// Pick one (or none)
"browser_action": {
"default_icon": "icon.png", // optional
"default_title": "WP Debug", // optional; shown in tooltip
"popup": "popup.html"
},
"permissions": [ "http://*/", "https://*/", "tabs" ],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js" ],
"run_at": "document_idle"
}
]
}
Your popup needs to send a message to your content script which then gathers up the hidden field info and sends the response back to the popup.
Here is an example:
popup.html
<html>
<head>
<script>
function readIds() {
console.log('Send request to content script');
document.getElementById("response").innerText = "Requesting...";
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id, {cmd: "readIds"}, function(response){
console.log('Response from page is:' + response);
document.getElementById("response").innerText = JSON.stringify(response);
});
});
}
</script>
</head>
<body style="width:400px;">
Click to read ids
<pre id="response"></pre>
</body>
</html>
content_script.js
// add a listener to get messages from background, popup
chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
switch (request.cmd) {
case "readIds":
console.log("readIds", request);
//TODO: Get real values to send from page
//e.g. document.getElementById("someid") etc
sendResponse({refCode:1, productCode: 2, productName: 3});
break;
}
});
mainfest.json
{
// Required
"name": "Foo Extension",
"version": "0.0.1",
// Recommended
"description": "A plain text description",
"icons": { "48": "foo.png" },
//"default_locale": "en",
// Pick one (or none)
"browser_action": {
"default_icon": "Foo.png", // optional
"default_title": "Foo Extension", // optional; shown in tooltip
"popup": "popup.html"
},
"permissions": [ "http://*/", "https://*/", "tabs" ],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js" ],
"run_at": "document_idle"
}
]
}
See documentation: http://code.google.com/chrome/extensions/messaging.html

Resources