invoke active tab in code chrome extension for tab capture - google-chrome

I would like to do tab capture by postmessage in chrome.
Below is the code that I have created.
The message will be sent by the content script.
Once the message is received, it will try to capture the current tab.
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(message,sender){
chrome.tabs.query({"active": true, "currentWindow": true}, function(tab) {
chrome.tabCapture.capture(captureOptions,
function(stream) {
mediaRecorder = new MediaRecorder(stream, options);
if (stream && message.status == 'started') {
var options = {mimeType: "video/webm"};
mediaRecorder.start();
mediaRecorder.ondataavailable = function(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
var blob = new Blob(recordedChunks, {
type: 'video/mp4'
});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
a.href = url;
a.download = 'test.webm';
a.click();
window.URL.revokeObjectURL(url);
stream.getVideoTracks()[0].stop();
}
}
}else if(message.status = "stopped"){
mediaRecorder.stop();
}
}
);
});
});
});
With the code above I am getting the Error
Unchecked runtime.lastError while running tabCapture.capture: Extension has not been invoked for the current page (see activeTab permission). Chrome pages cannot be captured.
at Object.callback (chrome-extension://haogilhkbanjpnkjbdgnefdgllfhldci/background.js:32:31)
Is there a way to bypass this?

Related

How can i make the HTML file open in Chrome while the calling browser is Explorer

I have this HTML (attached).
It is called by a web app that still works on I.E (for at least one or two months) due to some problems we have with the vendor.
The web app calls this HTML and it is opened in I.E also.
I need this HTML to be opened in Chrome.
Is there a way i can do this by adding something to the HTML itself?
<html>
<head>
<script>
async function setSRC(){
try{
var xhr;
const params = new Proxy(new URLSearchParams(window.location.search),
{
get: (searchParams, prop) => searchParams.get(prop),
});
var docId = params.docId;
var url = "``http://wsp-exttest.lcardtest.corp:4440/rest.oms/MaxRestService/getPDF?docId=``" + docId;
let response = await new Promise(resolve => {
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
resolve(xhr.response);
};
xhr.onerror = function () {
resolve(undefined);
console.error("** An error occurred during the XMLHttpRequest");
};
xhr.send();
})
//
var j = JSON.parse(xhr.responseText);
var pdfData = j[0].content;
var letterFrame = document.getElementById("letterFrame");
letterFrame.src = "data:application/pdf;base64," + pdfData;
/*letterFrame.onreadystatechange = () => {
if (letterFrame.readyState === 'complete') {
alert(letterFrame.readyState);
letterFrame.src = "data:application/pdf;base64," + pdfData;
}
};*/
}
catch(e)
{
if(confirm("Load faile: " + e.message + "click ok to retry"))
setSRC();
}
}
</script>
</head>
<body onload="setSRC()">
<iframe id="letterFrame" width="1200px" height="800px" onload=""></iframe>
Reload
</body>
</html>
Reload

OnHistoryStateUpdated creates chrome extension only when accessing Facebook

The code was changed to this code after using the on-updated event several times.OnHistoryStateUpdated is exactly what condition?
background.js
chrome.webNavigation.onHistoryStateUpdated.addListener(function (details) {
var domain = details.url;
var google = 'https://www.google.co.kr/';
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200 || xhr.status === 201) {
console.log(xhr.responseText);
} else {
console.error(xhr.responseText);
}
};
xhr.open('POST', 'http://soylatte.kr:3000/image/check');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('url=' + domain);
})

gcm push notification: not showing actual message reopen the browser

Gcm push notification message is sending properly to endpoints when browser is open :Notification messages which are in json file.
serviceWorker.js
'use strict';
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
console.log('Activated', event);
});
self.addEventListener('push', function(event) {
console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
});
self.addEventListener('activate', function(event) {
console.log('Activated', event);
});
self.addEventListener('push', function(event) {
var url = "http://localhost/pntest/gmpush1.json?param="+Math.random();
event.waitUntil(
fetch(url).then(function(response) {
if (response.status !== 200) {
console.log('Problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var promises = [];
for(var i=0; data.notification && i < data.notification.length; i++) {
promises.push(self.registration.showNotification(data.notification[i].title, {
body: data.notification[i].body,
'renotify': true,
icon: data.notification[i].icon
//tag: notification.tag
}));
}
return Promise.all( promises );
});
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log('Notification click: tag ', event.notification.tag);
event.notification.close();
var newurl = event.notification.data.newurl;
console.log(newurl.updatedurl);
var url = newurl.updatedurl;
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(windowClients) {
console.log(url);
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
});
gcmpush1.json
{"notification": [{"body": "Test data", "url": "https://www.google.com/", "icon": "http://www.wired.com/wp-content/uploads/2015/09/google-logo-1200x630.jpg", "title": "Test Notification"}]}
When browser is open, It's showing original message
Test Notification
If client browser is in offline(not opened) while my curl trigger. When reopening the client browser i suppose to get original message but what i'm getting is
site has been updated in the background
In my curl call, I have used 'time_to_live' = 2419200.
Whenever notification failed to load data to show on chrome notification window and 'PUSH' event generate successfully. It will show "site has been updated in the background". (Nothing to do with notification delivery from Curl. it may be fine)
Couple of observations from you service worker code:
1). You are using localhost path to fetch data, will create problem to load notification data while localhost will be offline.
var url = "http://localhost/pntest/gmpush1.json?param="+Math.random();
2). You are using two 'PUSH' event code in your SW. can wrap work in one function.
self.addEventListener('push', function(event) {...
You can refer below URL for creating simple service worker to get dynamic data for push notification.
https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web?hl=en

How to show only one notification in Chrome

I have created Chrome extension and use pusher to receive some data from server.
When I test it show multiple duplicate data because it follow tabs that I opened.
anyone understand me.Help me please.Thank you in advance.
Content.js
Pusher.Util.getLocalStorage = function()
{
return undefined;
}
Pusher.ScriptRequest.prototype.send = function(receiver) {
var xhr = new XMLHttpRequest();
xhr.open("GET", this.src, true);
xhr.send();
}
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
var pusher = new Pusher('xxxxxxxxxxxxxxxxxxxxx');
var notificationsChannel = pusher.subscribe('notifications');
notificationsChannel.bind('new_notification', function(notification){
// assign the notification's message to a <div></div>
var message = notification.message;
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
console.log(message);
var notification = new Notification('แจ้งเตือน', {
icon: 'img/LOGO.png',
body: message,
});
notification.onclick = function () {
location.reload();
};
}
});
duplicate notification

Fileupload using Filereader in chrome

I have to upload a file from the local memory of application (HTML5 File api). Onselect, the user should be able to upload directly without any question. The idea is to manage download/upload seamless to the user. Here is the code :
$("body").on("click", ".upload-file", function(e){
var fileToUpload = $('input:radio[name=optionsRadios]:checked').val();
var formData = new FormData();
$('input:radio[name=optionsRadios]:checked').parent().parent().parent().remove();
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 50*1024*1024, initFS, errorHandler);
var reader = new FileReader();
function initFS(fs){
fs.root.getDirectory('/', {}, function(dirEntry){
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {
for(var key = 0; key < entries.length; key++) {
var entry = entries[key];
if (entry.isFile){
var name = entry.name;
if(name == fileToUpload){
getAsText(entry.toURL());
formData.append('file', entry.toURL);
break;
}
}
}
}, errorHandler);
}, errorHandler);
}
function errorHandler(){
console.log('An error occured');
}
function getAsText(readFile) {
alert ("getting as text :" +readFile);
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsText(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = updateProgress;
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt) {
// Obtain the read file data
alert("loaded file");
var fileString = evt.target.result;
// Handle UTF-16 file dump
if(utils.regexp.isChinese(fileString)) {
//Chinese Characters + Name validation
}
else {
// run other charset test
}
// xhr.send(fileString)
}
var serverurl = "/fileserver/uploadFile?selpath="+fileToUpload;
var xhr = new XMLHttpRequest();
xhr.open('POST', serverurl);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
});
Now, I am trying to read the file as text (its a bad practice but wanted to find someway to make it work) but it doesn't throw any events. Can you please help me to find where I am going wrong ?