Chrome Extension: Messaging content script from an opened window - javascript

I am building a Chrome extension, and in my case, I need "popup.html" to sometimes appear and sometimes disappear, without having the user to click on the extension's icon. I have found this answer, which explains that you can open the popup page using "window.open" instead.
That seemed like a good solution for me, especially because I don't want to open "popup.html" in a new tab. It has to be on the current tab, and I shall simply play with its visibility.
The problem is: After opening "popup.html" as a new window, by using the following command inside "background.js":
window.open("popup.html", "extension_popup", "width=300,height=400,status=no,scrollbars=yes,resizable=no");
Which indeed makes "popup.html" to appear as expected, I simply cannot use it to send messages to the content script. What do I mean? inside "popup.html" I have some logic, and when a button is clicked, a function is invoked in "background.js". Then "background.js" sends a message to the content script this way:
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "doSomething"});
})
Problem is, nothing happens and the message is not sent.
On the other hand, when "popup.html" is opened in a regular way by pressing on the extension's icon, the message does passes on to the content script and the logic works as expected. It does not work only when "popup.html" is opened by "window.open".
Is what I'm trying to achieve possible at all? My guess is that "background.js" does not really function as a background page for the extension when I open popup.html by using "window.open(..)".
Help is much appreciated,
Thanks

Related

OnMessage Listener in background script [duplicate]

I just started out with Google Chrome extensions and I can't seem to log to console from my background js. When an error occurs (because of a syntax error, for example), I can't find any error messages either.
My manifest file:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"pageCapture",
"tabs"
]
}
background.js:
alert("here");
console.log("Hello, world!")
When I load the extension, the alert comes up but I don't see anything being logged to console. What am I doing wrong?
You're looking at the wrong place. These console messages do not appear in the web page, but in the invisible background page (ManifestV2) or service worker (ManifestV3).
To view the correct console open devtools for the background script's context:
Visit chrome://extensions/ or right-click the extension icon and select "Manage extensions".
Enable developer mode
Click on the link named background page (ManifestV2) or service worker (ManifestV3).
Screenshot for ManifestV2 extensions:
Screenshot for ManifestV3 extensions:
I had the same problem, in my case the logging was set to "Hide all" in the console tab in Chrome Developer tools.
I had not even realised this was an option, and I can't remember turning it off
For followers who wish to see the debug console for a "content script" of their chrome extension, it is available by doing a normal "show developer console" then use the dropdown arrow to selects its "javascript environment" then you'll have access to its methods, etc.
additionally
if you want to see content_script js file ( when "background" property is not set ) in manifest.json
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["popup.js"],
}]
"browser_action": {
"default_icon": "icon_32.png",
"default_popup": "popup.html"
}
then right click on extension icon and click on Inspect popup and developer window opens with popup.html opened , there you see console tab.
Similar to the answer of Michiel i also had a funny console configuration: A filter i dont remember setting:
After clearing the filter i saw the messages.
I had this problem as well. It seems as though my webpage was not updating to the newly saved script. This was solved by pressing Ctrl + refresh (or Ctrl + F5) in the chrome browser.
If we want to read messages printed to console from the popup page, we can click the extension icon to open the popup page, then do right click on the popup page anywhere, a dropdown menu will display, we just click "Inspect" menu to open the developer tool. Notice that the popup page must be keep opening. If it is closed(by window.close()), the developer tool will be closed too.
The other answer(s) work(s) for background.js but, if you are looking for console.logs from the popup then you can try:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
I was developing using cra, and this worked for me.
For those developing extensions for Firefox:
TL;DR version: you need to use Ctrl+Shift+J to call up the browser console window, and click on the settings icon on the top right-hand corner and make sure that "Show Content Messages" is checked.
Longer explanation from a related stackoverflow question: How do I see the console.log output of a background script in a Firefox WebExtension?

chrome extension eventpage onclicked not triggering [duplicate]

I just started out with Google Chrome extensions and I can't seem to log to console from my background js. When an error occurs (because of a syntax error, for example), I can't find any error messages either.
My manifest file:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"pageCapture",
"tabs"
]
}
background.js:
alert("here");
console.log("Hello, world!")
When I load the extension, the alert comes up but I don't see anything being logged to console. What am I doing wrong?
You're looking at the wrong place. These console messages do not appear in the web page, but in the invisible background page (ManifestV2) or service worker (ManifestV3).
To view the correct console open devtools for the background script's context:
Visit chrome://extensions/ or right-click the extension icon and select "Manage extensions".
Enable developer mode
Click on the link named background page (ManifestV2) or service worker (ManifestV3).
Screenshot for ManifestV2 extensions:
Screenshot for ManifestV3 extensions:
I had the same problem, in my case the logging was set to "Hide all" in the console tab in Chrome Developer tools.
I had not even realised this was an option, and I can't remember turning it off
For followers who wish to see the debug console for a "content script" of their chrome extension, it is available by doing a normal "show developer console" then use the dropdown arrow to selects its "javascript environment" then you'll have access to its methods, etc.
additionally
if you want to see content_script js file ( when "background" property is not set ) in manifest.json
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["popup.js"],
}]
"browser_action": {
"default_icon": "icon_32.png",
"default_popup": "popup.html"
}
then right click on extension icon and click on Inspect popup and developer window opens with popup.html opened , there you see console tab.
Similar to the answer of Michiel i also had a funny console configuration: A filter i dont remember setting:
After clearing the filter i saw the messages.
I had this problem as well. It seems as though my webpage was not updating to the newly saved script. This was solved by pressing Ctrl + refresh (or Ctrl + F5) in the chrome browser.
If we want to read messages printed to console from the popup page, we can click the extension icon to open the popup page, then do right click on the popup page anywhere, a dropdown menu will display, we just click "Inspect" menu to open the developer tool. Notice that the popup page must be keep opening. If it is closed(by window.close()), the developer tool will be closed too.
The other answer(s) work(s) for background.js but, if you are looking for console.logs from the popup then you can try:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
I was developing using cra, and this worked for me.
For those developing extensions for Firefox:
TL;DR version: you need to use Ctrl+Shift+J to call up the browser console window, and click on the settings icon on the top right-hand corner and make sure that "Show Content Messages" is checked.
Longer explanation from a related stackoverflow question: How do I see the console.log output of a background script in a Firefox WebExtension?

Chrome extension onMessage listener not working [duplicate]

I just started out with Google Chrome extensions and I can't seem to log to console from my background js. When an error occurs (because of a syntax error, for example), I can't find any error messages either.
My manifest file:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"pageCapture",
"tabs"
]
}
background.js:
alert("here");
console.log("Hello, world!")
When I load the extension, the alert comes up but I don't see anything being logged to console. What am I doing wrong?
You're looking at the wrong place. These console messages do not appear in the web page, but in the invisible background page (ManifestV2) or service worker (ManifestV3).
To view the correct console open devtools for the background script's context:
Visit chrome://extensions/ or right-click the extension icon and select "Manage extensions".
Enable developer mode
Click on the link named background page (ManifestV2) or service worker (ManifestV3).
Screenshot for ManifestV2 extensions:
Screenshot for ManifestV3 extensions:
I had the same problem, in my case the logging was set to "Hide all" in the console tab in Chrome Developer tools.
I had not even realised this was an option, and I can't remember turning it off
For followers who wish to see the debug console for a "content script" of their chrome extension, it is available by doing a normal "show developer console" then use the dropdown arrow to selects its "javascript environment" then you'll have access to its methods, etc.
additionally
if you want to see content_script js file ( when "background" property is not set ) in manifest.json
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["popup.js"],
}]
"browser_action": {
"default_icon": "icon_32.png",
"default_popup": "popup.html"
}
then right click on extension icon and click on Inspect popup and developer window opens with popup.html opened , there you see console tab.
Similar to the answer of Michiel i also had a funny console configuration: A filter i dont remember setting:
After clearing the filter i saw the messages.
I had this problem as well. It seems as though my webpage was not updating to the newly saved script. This was solved by pressing Ctrl + refresh (or Ctrl + F5) in the chrome browser.
If we want to read messages printed to console from the popup page, we can click the extension icon to open the popup page, then do right click on the popup page anywhere, a dropdown menu will display, we just click "Inspect" menu to open the developer tool. Notice that the popup page must be keep opening. If it is closed(by window.close()), the developer tool will be closed too.
The other answer(s) work(s) for background.js but, if you are looking for console.logs from the popup then you can try:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
I was developing using cra, and this worked for me.
For those developing extensions for Firefox:
TL;DR version: you need to use Ctrl+Shift+J to call up the browser console window, and click on the settings icon on the top right-hand corner and make sure that "Show Content Messages" is checked.
Longer explanation from a related stackoverflow question: How do I see the console.log output of a background script in a Firefox WebExtension?

Popup not showing in Chrome Extension, but firing all events when clicking icon

I have been struggling with this issue since yesterday and I have run out of ideas to figure out what is going on.
I am developing a Chrome extension with a popup menu with a few buttons to fire certain events. The problem is that instead of showing the popup.html when clicking the icon extension, it just fires all associated events with the buttons.
My original extension had a persistent background script, so when I was debuggin it, the error that showed up was "cannot read property 'addeventlistener' of null". I have already looked it up and, apparently, it had to do with the position of the script src line inside the popup.html file. I tried relocating it but nothing changed.
After trying many alternatives to do the same in other ways and comparing my code with other sample extensions, I created a very simple extension to demonstrate the trouble I am dealing with. It's just a three-buttons popup and when you click each button, a message should appear showing some text. The files are:
popup.html
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<button id="OpenButton">Open</button>
<button id="StartButton">Start</button>
<button id="StopButton">Stop</button>
</body>
</html>
popup.js
function open(){alert("open");}
function start(){alert("start");}
function stop(){alert("stop");}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('OpenButton').addEventListener(
'click', open());
document.getElementById('StartButton').addEventListener(
'click', start());
document.getElementById('StopButton').addEventListener(
'click', stop());
});
manifest.json
{
"name": "A browser action with a popup that displays a message",
"description": "Display a message",
"version": "1.0",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"browser_action": {
"default_title": "Display this message.",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
Basically, I took a sample extension (it offered a popup with 4 buttons to change the background colour of the current page) and edited it. This extension worked fine, but in this new extension I made, when you click the extension icon, all three messages are displayed, one after another and no popup shows up.
I can't see where the conflict is and I couldn't find any question with the same issue. Any suggestion is really appreciated.
Regards.
Opening an alert() causes the popup window to lose focus.
Which, in turn, immediately closes it.
Don't use alert() in the popup - to debug, use console.log(), the output of which is accessible if you right-click your extension's browser action and select "Inspect popup".

google chrome extension jquery not loaded

In the following google chrome extension file why do i cannot use a jquery script inside myscript.js file,Is jquery not loaded inside myscript.js file, what changes should be done in manifest file to use jquery inside myscript.js
Manifest.json
{
"manifest_version": 2,
"name": "One-click Kittens",
"description": "This extension demonstrates a browser action with kittens.",
"version": "1.0",
"background": { "scripts": ["jquery-1.9.1.min.js","myscript.js"] },
"permissions": [
"tabs", "http://*/*"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
myscript.js
alert($("#extension-command-list").val()); //undefined
alert($("#extension-command-list").html()); //undefined
$(document).ready(function() {
alert("hello world"); //not seen
});
EDIT:
"background": { "scripts": ["jquery-1.9.1.min.js"] },
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["myscript.js"] or "js": ["jquery-1.9.1.min.js","myscript.js"]
}
],
The reason you are getting undefined is becaus you are not specifying a background page.
So.. the background page Chrome generates, looks just like
<html>
<head></head>
<body>
<script src="jquery-1.9.1.min.js"></script>
<script src="myscript.js"></script>
</body>
</html>
As you see there isn't any Element which can be selected, thats why your first too alert's return undefined.
Anyway, the alert("hello world") should be shown too, as the DOMContentLoaded or similar should be fired any way.
Could it be that you want to select Elements of an site you are visiting ?
If so, you should put myscript.js in an Content Script instead of a background page.
There you get access to the DOM of the site.
So the question is, what are you up to ?
If you actually want to select Elements in your background page, you have to specify one,
Looking at the background pages site shows you, its as easy as:
{
"name": "My extension",
...
"background": {
"page": "background.html"
},
...
}
Edit:
"default_popup" : "popup.html"
Refers to a Browser Actions Popup. A browser Action is used
[...] to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can also have a tooltip, a badge, and a popup.
So
If a browser action has a popup, the popup appears when the user clicks the icon. The popup can contain any HTML contents that you like, and it's automatically sized to fit its contents.
To add a popup to your browser action, create an HTML file with the popup's contents. Specify the HTML file in the default_popup field of browser_action in the manifest, or call the setPopup method.
"background":"{...}"
A common need for extensions is to have a single long-running script to manage some task or state. Background pages to the rescue.
As the architecture overview explains, the background page is an HTML page that runs in the extension process. It exists for the lifetime of your extension, and only one instance of it at a time is active.
Also has a background script access to all parts of the Chrome Extension's Api. chrome.* if you have requested the permissions respectively
Now lets say, you want to for example extend the ContextMenu of chrome with some functionalities.
To do this, you first have create a contextMenuEntry in the background page.
And just like your background page has only one instance of it running at a time, and that for the lifetime of the extension, so should your contextMenuEntry only have one instance of it, which gets created when your extension runs and remains for the lifetime of your extension.
Now assume you want to display the currently selected text of the page you are visiting in one of you Menu Entries.
To do that, you need access to the chrome.contextMenus API Method but a contentscript is not allowed to use this.
To get this to work you need to pass a message with the selected text to the background page through e.g. chrome.extension.sendMessage
In the background page you can then update your existing contextmenuentry to display the selected text.
sry i couldn't think of a better example right now

Categories