Message listener only begins firing after browserAction has been clicked - google-chrome-extension

It appears that a message from content to background only begins firing after backgroundAction has been run at least once.
In the below code example, a click on browserAction turns the page red, and a click on the page body turns the page blue (via a message sent by the content script).
If I click the page body first, nothing happens. It only begins working after I've clicked browserAction once.
Why is this happening and how can I make it so the message listener fires without having browserAction run first?
Any help would be greatly appreciated!
content.js
$(function(){
$('body').on('click', function() {
// Send a message to background.js
chrome.runtime.sendMessage(true, function(response){
console.log(response);
});
});
});
background.js
// Make background red when browserAction is cliked
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.executeScript( {
code: 'document.body.style.backgroundColor="red"'
});
});
// Make background blue when any message is received
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse){
chrome.tabs.executeScript( {
code: 'document.body.style.backgroundColor="blue"'
});
return true;
})

As always in such cases use the debugger. The error I'm seeing here in the extension's background page console which can be opened on chrome://extensions page:
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "...". Extension manifest must request permission to access this host.
When runtime.onMessage is executed after a message from the content script Chrome doesn't know that executeScript was initiated by a user action so the code is blocked.
As for browserAction.onClicked, it is always invoked on user's interaction so "permissions": ["activeTab"] is sufficient for the code executed in the eventjob context of the issued click. And it creates temporary permission to modify the active tab, see the documentation:
The following user gestures enable activeTab:
Executing a browser action
Executing a page action
Executing a context menu item
Executing a keyboard shortcut from the commands API
Accepting a suggestion from the omnibox API
Solution #1 (the best) would be to avoid injecting any code from the background script and do everything in the content script based on messages from the background script.
Solution #2 would be to add the required permission to manifest.json:
"permissions": ["activeTab", "<all_urls>"]

Related

Chrome extension loses activeTab permission

I have an extension that, when the "browser action" (the icon next to the address bar) is clicked, executes a script on the current tab's page:
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
file: 'controls.js'
});
});
The controls.js injects some stuff into the DOM so that the user can press a key to tell background.js to set up a WebRTC connection and do other business-logic stuff.
Usually this works just fine. But sometimes the extension stops working on a tab if it has been open but not used for a while, I think typically after the computer has gone to sleep and woken again. When this happens, in the console for background.js, I get the error "Unchecked runtime.lastError: Cannot access contents of the page. Extension manifest must request permission to access the respective host."
Any idea why this could happen, or what I can do to catch this error and handle it to get permissions back?
It took me a lot of futzing around to figure this out.
If the user has been idle for a while, upon refreshing the page, the website I'm injecting JS into will redirect to an authentication site on another domain, which will then redirect the user back. It happens fast enough to not notice typically, but Chrome removes the activeTab permission when the domain changes.
I'm handling the permission loss by notifying the user through the badge text, more or less like this:
chrome.tabs.executeScript(tab.id, {
code: 'alert("hello activeTab")'
}, (result) => {
if (result === undefined) { // this means that activeTab permission is lost
console.log('lost activeTab permission :(');
chrome.browserAction.setBadgeText({
text: 'off',
tabId: tab.id
});
}
});

Chrome extension browserAction.onClicked not listening

I have the following in my background.js file which is referenced in manifest.json:
chrome.browserAction.onClicked.addListener(function (tab) {
console.log('browserAction clicked');
});
When I click on the browser action icon, I never see browserAction clicked printed to the console.
Am I misunderstanding how this is supposed to work?
Console.log doesn't work in background.js. Use
chrome.browserAction.onClicked.addListener(function (tab) {
alert('browserAction clicked');
});
instead of that.
To see the console messages that comes from the background.js
display the extension;
chrome://extensions/.
Make sure that developer mode is enabled
Click on the "Inspect Views"
of your background page
You should see console messages under the
console tab.
Does the browser action have a popup? If so, the event won't fire.

Chrome Extension + Getting Hang while any dialogue comes while opening a page

I have created one extension to test my website, which will open page and do some activity like set text, get text etc etc.
I have created one C# application and via websocket I will communicate with extension.
In my extension I have added listener as below,
document.addEventListener('DOMContentLoaded', function() {
websocket.send(""); // Send signal to C# to execute next command
});
so when I will open any website e.g www.google.com, it will fire above event and my next action will come to execute, but issue is while I open any website which will have alert box at the first stage of loading page, will never execute above listener e.g If I will open http://www.crowderassoc.com/javascript/alertbox.html, it will give you an alert message, till your click on OK, the page will be busy and so It will get stuck.
I am created automated script, in which I will place one MSAA command to click on that "OK" button, but my it just got hanged.
Is there any option that I can make it work in this situation?
Move code of DOMContentLoaded Listener
document.addEventListener('DOMContentLoaded', function() {
websocket.send(""); // Send signal to C# to execute next command
});
in Content Scripts to listener of tabs.onUpdated or any of webRequest, webNavigation Appropriate Listeners in Background Page.

Unable to use getBackgroundPage() api from a devtools extension

I am trying to write an extension that adds functionality to the Chrome devtools.
According to the devtools documentation, it says that the pages in devtools support very limited apis. Any API that is not supported can be access by accessing it through the background page, just as what contentscripts does.
Here is the relevant documentation snippet:
The tabId property provides the tab identifier that you can use with the chrome.tabs.* API calls. However, please note that chrome.tabs.* API is not exposed to the Developer Tools extension pages due to security considerations — you will need to pass the tab ID to the background page and invoke the chrome.tabs.* API functions from there.
Here is the source url: http://developer.chrome.com/extensions/devtools.inspectedWindow.html
However, when I try to do that, I get the following error in the console:
uncaught Error: "getBackgroundPage" can only be used in extension processes. See the content scripts documentation for more details.
Here is my code in my devtools.js script:
chrome.extension.getBackgroundPage().getLocation();
What am I doing wrong?
EDIT
I should describe my scenario first, and show how I am implementing it.
What I want to do is to display extra data in a devtools panel related to a webpage. In order to get that data, I will need to send a HTTP request in the same session as the page being debugged, because it requires authentication.
Use Case:
User browses to a particular URL. He is authenticated to the site. He then invokes devtools. The devtools panel opens up and a new panel shows up that has extra data related to the page.
Implementation:
1) DevTools script finds out the url of the page being inspected. If the url matches the site base hostname, then it opens a panel. In the callback of the panel creation, it sends a message to a background page, asking it to download a JSON payload from a debug endpoint on the same site, and then sends it to the devtools extension, wh ich then displays it.
Problems:
1) The background page gets the request, and downloads the URL. However the download is not using the same session as the user, so the download request fails.
2) From devtools window, I got the tabId of the inspected window. I send this tabId to the background page so that it can parse some stuff out of the url. However, chrome.tabs.get(tabId) does not return the tab.
To summarize, I need to
1) Get the background page to download data in the same session as the user's tab that is being debugged.
2) I need to have the background page be able to get access to the user's tab.
The APIs available to extension pages within the Developer Tools window include all devtools modules listed above and chrome.extension API. Other extension APIs are not available to the Developer Tools pages, but you may invoke them by sending a request to the background page of your extension, similarly to how it's done in the content scripts.
I guess the documentation is little ambiguous, By chrome.extension API they mean the Supported API's for content scripts.
So, you can use long lived communication for communication between inspected page and background page
Demonstration:
The following code illustrate scenario where a devtools page need some information from background page, it uses messages for communication.
manifest.json
Ensured permissions are all available in manifest file
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"devtools_page":"devtools.html",
"manifest_version":2,
"version":"2",
"permissions":["experimental"],
"background":{
"scripts" : ["background.js"]
}
}
devtools.html
A trivial HTML File
<html>
<head>
<script src="devtools.js"></script>
</head>
<body>
</body>
</html>
devtools.js
Used Long lived Communication API's
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Request Tab Data");
port.onMessage.addListener(function (msg) {
console.log("Tab Data recieved is " + msg);
});
background.js
Responded to communication request and passed trivial information using tab API()'s
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"active": true
}, function (tabs) {
port.postMessage(tabs[0].id);
});
console.log("Message recived is "+message);
});
});
Sample Output received for trivial devtools.js here
Let me know if you need more information
EDIT 1)
For your question 1)
Can you make you call(s) from browser extension HTML Page\Content Script so same session is shared, i have tried both the ways in a sample and it is working form me, instead of code in background page- make the code in content script or browser action HTML Page.
Let me know if you are still facing problems.
For your question 2)
The following code always fetches current window user is browsing
manifest.json
Ensure you have tabs permission in your manifest.
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"manifest_version":2,
"version":"2",
"permissions":["tabs"],
"background":{
"scripts" : ["background.js"]
}
}
background.js
chrome.tabs.query({
"status": "complete", // Window load is completed
"currentWindow": true, // It is in current window
"active": true //Window user is browsing
}, function (tabs) {
for (tab in tabs) { // It returns array so used a loop to iterate over items
console.log(tabs[tab].id); // Catch tab id
}
});
Let me know if you are still unable to get tab id of current window.

Google Chrome Extension- Messages + call to function between popup page and content script

In a Google Chrome extension I want to pass messages between a content script and a popup page. I also want a function in the content script to be fired when a signal to do this is sent by the popup page to the content script.
The section in Google Chrome Extensions developer docs for messages, states that messages can be passed "from your content script to an extension page, or vice versa" (quoted from http://code.google.com/chrome/extensions/messaging.html )
Does this mean that I can send/receive messages between the content script and the popup page? Because the usage I have seen is for communication between background page and content script.
Or do I have to set up a 3 - way message passing route-- viz.
content script <--> background page <--> popup page. And if this is the case, how do I set up messaging between background page <--> popup page?
And how do I fire a function in the content script, after sending signal to content script from the popup page? Does this also require background script to be present?
Content scripts can only send a message to the background page. If you want to send a message from a content script to a popup, you have to:
Send the message from the Content script to the background page.
chrome.runtime.sendMessage( ...message... , function() { /*response*/ });
Receive the message at the background.
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { ... });
Pass the message to the popup. To get a reference to the global window object of the popup, use chrome.extension.getViews. Note: Unlike most of the other chrome APIs, this method is synchronous:
var popupWindows = chrome.extension.getViews({type:'popup'});
if (popupWindows.length) { // A popup has been found
// details is the object from the onMessage event (see 2)
popupWindows[0].whatever(message, sendResponse);
}
In the popup, define the whatever method.
function whatever(message, sendResponse) {
// Do something, for example, sending the message back
sendResponse(message);
}
When sendResponse (4) is called, details.sendResponse (see 3) is called. This, in turn, calls function() { /*response*/ } from 1.
Note: chrome.runtime.sendMessage/onMessage is only supported in Chrome 26+. Use chrome.extension.sendMessage if you want to support older browsers as well.

Resources