Chrome extension: (DOM)Debugger API does not work anymore - google-chrome

Our chrome extension does not work correctly anymore since version 37.0.2062.103 (It used to work correctly on chrome version 36.0.1985.143).
Specifically, the debugger API has stopped working for us when we use the DOMDebugger.
See the attached code: (background.js)
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if( changeInfo.status == "loading" && tab.active){
var debugId = {tabId:tabId};
chrome.debugger.attach(debugId, '1.0', function() {
chrome.debugger.sendCommand(debugId, 'Debugger.enable', {}, function() {
chrome.debugger.sendCommand(debugId, "DOMDebugger.setEventListenerBreakpoint", {'eventName':'click'},
function(result) {
console.log('registering click');
});
});
});
}
});
chrome.debugger.onEvent.addListener(onEvent);
function onEvent(debuggeeId, method,params) {
if(method=="Debugger.paused"){
console.log('DONE!');
}
};
The extension successfully starts the debugger. we get the yellow debugger ribbon.
We also see the 'registering click' msg in the console. the result argument is an empty object {} (line 8).
However upon clicking on a button that has a click event listener nothing happens.
It used to work without any issues.

It seems like it regressed with https://codereview.chromium.org/305753005. One needs to call "DOM.enable" for it to work now. On the Chrome side, we should implicitly enable DOM domain upon setEventListenerBreakpoint for backwards compatibility. Unfortunately it already squeezed into the stable release.

Related

Detect if another browser tab is using speechRecognition

Is it possible to tell if another Chrome tab is using webkitSpeechRecognition?
If you try to use webkitSpeechRecognition while another tab is using it, it will throw an error "aborted" without any message. I want to be able to know if webkitSpeechRecognition is open in another tab, and if so, throw a better error that could notify the user.
Unless your customer is on the same website(you could check by logging the ip/browserprint in database and requesting by json) you cannot do that.
Cross domain protection is in effect, and that lets you know zilch about what happens in other tabs or frames.
I am using webkitSpeechRecognition for chrome ( does not work on FF) and I faced same issues like multiple Chrome tabs. Until the browser implement a better error message a temporary solutions that work for me:
You need to detect when a tab is focused or not in Chrome using
Javascript.
Make javascript code like this
isChromium = window.chrome;
if(isChromium)
{
if (window.addEventListener)
{
// bind focus event
window.addEventListener("focus", function (event)
{
console.log("Browser tab focus..");
recognition.stop();// to avoid error
recognition.start();
}, false);
window.addEventListener("blur", function (event)
{
console.log("Browser tab blur..");
recognition.stop();
}, false);
}
}
There's a small workaround for it. You can store the timestamp in a variable upon activating SpeechRecognition and when it exits after a few seconds of inactivity, it will be compared to a timestamp since the SpeechRecognition was activated. Since two tabs are using the API simultaneously, it will exit immediately.
For Chrome, you can use the code below and modify it base on your needs. Firefox doesn't support this yet at the moment.
var transcriptionStartTime;
var timeSinceLastStart;
function configureRecognition(){
var webkitSpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition;
if ('webkitSpeechRecognition' in window) {
recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = "en-US";
recognition.onend = function() {
timeSinceLastStart = new Date().getTime() - transcriptionStartTime;
if (timeSinceLastStart < 100) {
alert('Speech recognition failed to start. Please close the tab that is currently using it.');
}
}
}
}
See browser compatibility here: https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition

geoLocation.GetCurrentPosition always fails in IE 11

The script below works fine in FireFox and Chrome, but in Internet Explorer 11, it always fails (with POSITION_UNAVAILABLE).
I have set the browser to allow requests for position, and I agree to the prompt the browser presents me when requesting permission.
I'm almost certain that this worked fine a few months ago when I was last experimenting with it. What could I be missing as far as IE's settings?
<script type="text/javascript">
$(document).ready(function () {
if (Modernizr.geolocation)
{
navigator.geolocation.getCurrentPosition(positionSuccess, positionError, { enableHighAccuracy: true, maximumAge: 60000, timeout: 10000 })
}
else
{
$("#GeoError").html("Unable to retrieve current position.")
}
});
function positionSuccess(position)
{
$("#Latitude").val(position.coords.latitude);
$("#Longitude").val(position.coords.longitude);
}
function positionError(error)
{
var message = "";
// Check for known errors
switch (error.code) {
case error.PERMISSION_DENIED:
message = "This website does not have your permission to use the Geolocation API";
break;
case error.POSITION_UNAVAILABLE:
message = "Your current position could not be determined.";
break;
case error.PERMISSION_DENIED_TIMEOUT:
message = "Your current position could not be determined within the specified timeout period.";
break;
}
// If it's an unknown error, build a message that includes
// information that helps identify the situation, so that
// the error handler can be updated.
if (message == "") {
var strErrorCode = error.code.toString();
message = "Your position could not be determined due to " +
"an unknown error (Code: " + strErrorCode + ").";
}
$("#GeoError").html(message)
}
</script>
Also, I get the same failure in IE11 when I try http://html5demos.com/geo, where both FireFox and Chrome work fine.
Does you enable the Location Service?
I have had the same issue, it worked after I enabled the Location Service in my windows 2016.
This page shows how to enable the Location Service in windows 10.
I have had the same issue in IE11 only.
I had to set enableHighAccuracy to false to get it to work. Once I did that IE worked as expected.
In Internet Options, click on the Privacy tab. Uncheck the Never allow websites to request your physical location box, hit on OK.
After making these changes, the http://html5demos.com/geo now worked for me. Initially it didn't.
aha, just discovered something.
Chrome apparently uses the WIFI access points to help finding the location.
IE11 (and edge) just falls back to the default location in your windows settings, if there is no immediate GPS signal.

window.onerror not working in chrome

I am trying to add an onerror event to my website.
window.onerror = function() {
alert("an error");
}
But all I receive is:
notThere();
ReferenceError: notThere is not defined
What am I missing?
Browser: Chrome 26.0.1410.64 m
Steps to reproduce:
add the code to the console.
add notThere() to the console
window.onerror is not triggered when the console directly generates an error. It can be triggered via setTimeout though, e.g., setTimeout(function() { notThere(); }, 0);
Possible duplicate: Chrome: Will an error in code invoked from the dev console trigger window.onerror?
The window.onerror works in Chrome (see jsfiddle - http://jsfiddle.net/PWSDF/), but apparently not in the console - which makes some sense.
Some other reasons that you may not be able to handle errors in window.onerror (apart from the mentioned ones):
Another library sets window.onerror after you.
If you are using Angular, errors wont pass through window.onerror. You have to handle them using this factory:
.factory('$exceptionHandler', function() {
return function errorCatcherHandler(exception, cause) {
console.error(exception);
if (window.OnClientError) window.OnClientError(exception);
};
})
See:
https://docs.angularjs.org/api/ng/service/$exceptionHandler
http://bahmutov.calepin.co/catch-all-errors-in-angular-app.html

Background page to communicate with Content Script

I'm having a bit of trouble getting some final bit of code working to complete my extension.
The short version is that I need my background.html page to notify my content script whenever a different tab is selected. At the moment I have the following:
background.html
chrome.tabs.onSelectionChanged.addListener(function( tab_id , info ) {
// some way to call App.resize();
});
content script js file
var App = {
resize: function() {
// logic
}
}
The longer version is that I'm building a fullscreen extension for chrome that works the same as Firefox and Safari on PC. At the moment, when you enter fullscreen mode you can't really navigate to different other tabs unless you use a shortcut and cycle through all your open tabs. My extension shows all the currently opened tabs and you can switch to them, as well as an address bar so you can go to other websites, etc.
I have everything working as I need it, and it's all working nicely except with pages that redirect to others. E.g. with Google Reader, when you open an article in the background, it goes through google's proxy and then redirects to the actual article. This is the only place where it doesn't work. But if I can call the App.resize() function whenever I switch to a new tab, that will fix my problem. (I hope).
It depends on whether you need to inform content scripts on all pages or just the selected tab. I'll give you solutions for both.
background.html (if you need to inform all tabs)
chrome.tabs.onSelectionChanged.addListener(function() {
chrome.windows.getAll({populate: true}, function(windows) {
var w,t;
for (w=0; w<windows.length; w++) {
for (t=0; t<windows[w].tabs.length; t++) {
chrome.tabs.sendRequest(windows[w].tabs[t].id, "resize");
}
}
});
});
background.html (if you only need to inform the newly-selected tab)
chrome.tabs.onSelectionChanged.addListener(function(tabId) {
chrome.tabs.sendRequest(tabId, "resize");
});
content script
var App = {
resize: function() {
// logic
}
};
chrome.extension.onRequest.addListener(function(request) {
if (request === "resize") {
App.resize();
}
});

Open a "Help" page after Chrome extension is installed first time

I am new to Chrome extension. I have a question about how to make the extension to open a "Help" page automatically after installation. Currently, I am able to check whether the extension is running the first time or not by saving a value into localStorage. But this checking is only carried out when using click the icon on the tool bar. Just wondering if there is a way that likes FF extension which uses the javascript in to open a help page after the installation. Thanks.
Edit:
Thanks for the answer from davgothic. I have solved this problem.
I have another question about the popup. My extension checks the url of current tab,
if OK(url){
//open a tab and do something
}
else{
//display popup
}
Is it possible to show the popup in this way?
Check this updated and most reliable solution provided by Chrome: chrome.runtime Event
chrome.runtime.onInstalled.addListener(function (object) {
let externalUrl = "http://yoursite.com/";
let internalUrl = chrome.runtime.getURL("views/onboarding.html");
if (object.reason === chrome.runtime.OnInstalledReason.INSTALL) {
chrome.tabs.create({ url: externalUrl }, function (tab) {
console.log("New tab launched with http://yoursite.com/");
});
}
});
Add this to your background.js I mean the the page you defined on manifest like following,
....
"background": {
"scripts": ["background.js"],
"persistent": false
}
...
UPDATE: This method is no longer recommended. Please see Nuhil's more recent answer below.
I believe what you need to do is put something like this into a script in the <head> section of your extension's background page, e.g. background.html
function install_notice() {
if (localStorage.getItem('install_time'))
return;
var now = new Date().getTime();
localStorage.setItem('install_time', now);
chrome.tabs.create({url: "installed.html"});
}
install_notice();
As of now (Aug 2022) the right way to execute code on first install or update of an extension using Manifest V3 is by using the runtime.onInstalled event.
This event is documented here: https://developer.chrome.com/extensions/runtime#event-onInstalled
There is one example for this exact case in the docs now:
https://developer.chrome.com/docs/extensions/reference/tabs/#opening-an-extension-page-in-a-new-tab
Note: This example above is wrong as the callback function parameter is Object with the key reason and not reason directly.
And another example here (this one is correct but does not open a tab):
https://developer.chrome.com/docs/extensions/reference/runtime/#example-uninstall-url
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
// Code to be executed on first install
// eg. open a tab with a url
chrome.tabs.create({
url: "https://google.com"
});
} else if (details.reason === chrome.runtime.OnInstalledReason.UPDATE) {
// When extension is updated
} else if (details.reason === chrome.runtime.OnInstalledReason.CHROME_UPDATE) {
// When browser is updated
} else if (details.reason === chrome.runtime.OnInstalledReason.SHARED_MODULE_UPDATE) {
// When a shared module is updated
}
});
This code can be added to a background service worker: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/
It would be better to place a "version" number so you can know when an extension is updated or installed.
It has been answered here:
Detect Chrome extension first run / update
All you need to do is adding the snippet below to your background.js file
chrome.runtime.onInstalled.addListener(function (object) {
chrome.tabs.create({url: `chrome-extension://${chrome.runtime.id}/options.html`}, function (tab) {
console.log("options page opened");
});
});