chrome coverage report - is there any API to receive json file? - javascript

Lately i have discovered chrome coverage report that I find very useful.
https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage
The weakness of this tools is that it is single page scoped. But in version chrome 73 there is an option to generate json file for page that can be stored for further processing.
I would like to collect json data for multiple pages, than merge it and visualize in the context of single file (in my case stylesheet).
It would be great if I could receive json file directly through chrome (Extenstion?) API. So far i have found only this example: https://gist.github.com/krisselden/2487706bcbf37da26d4a89d0f74df768. But it seems to work only for browser remote mode.
Do you know is there any way to get coverage json report over chrome API?
Best regards
It Man.

Heres what i got so far (snippets only):
Got extension template form https://extensionizr.com
Inside background.js script have placed this raw method:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request.command);
if (request.command === "getCoverage") {
chrome.tabs.query(
{currentWindow: true, active : true},
function(tabArray){
var activeTab = tabArray[0];
console.log("tabid: " + activeTab.id)
chrome.debugger.attach( { tabId: activeTab.id }, "1.2", function() {
console.log("attached");
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.enable", undefined, function(result) {
console.log("ProfilerStarted:" ,result);
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.startPreciseCoverage", { callCount: true }, function(result) {
console.log("coverageStarted:" ,result);
setTimeout(function() {
chrome.debugger.sendCommand( { tabId: activeTab.id }, "Profiler.takePreciseCoverage", undefined, function(response) {
console.log(response.result);
});
}, 4000)
});
});
});
}
);
}
});
Inside browser_action.js:
document.getElementById("getCoverageSnapshot").addEventListener("click", function() {
chrome.extension.sendMessage({
command: "getCoverage"
});
});
And in browse_action.html:
<!doctype html>
<style type="text/css">
</style>
<button id="getCoverageSnapshot">Get Snapshot</button>
<script type="text/javascript" src="/src/browser_action/browser_action.js"></script>
When button clicked Profiler.takePreciseCoverage result can be recieved inside background.js.
Still looking the way to receive css coverage data...

Related

Angular resource get request is been canceled

I've got a small angulaerjs app that uses angularjs resource in one of it's controllers. Here is the code for resource usage
$scope.getFilteredTasks = function (filter) {
var resource = $resource('{0}/api/orderTasks/filterTasks'.format($scope.baseUrl), { status: '#status', type: '#type', createdDate: '#createdDate', agentType: '#agentType', page: '#page', pageSize: '#pageSize' }, {
'response': { method: 'GET', isArray: false }
});
$('#loading').show();
resource.response({
status: filter.status,
type: filter.type,
createdDate: filter.createdDate,
agentType: filter.agentType,
page: $scope.currentPage,
pageSize: $scope.pageSize
},
function (result) {
$scope.resultTasks = result.Items;
if ($scope.totalItems != result.TotalCount)
$scope.totalItems = result.TotalCount;
$('#loading').hide();
},
function (result) {
$('#loading').hide();
alert('Error in request!')
});
};
When the page first load everything is fine and i get all data that i need. But when I make second request (for example push the button on page that calls getFilteredTask(filter) function). I've got an result.status = -1. According to Fiddler and Chrome Network tab in dev tools request has status 200 but was cancelled. I've also checked the backend and found no problems, request was succsessfully handled and server returned all data that I need but I get cannceled request on client side.
UPDATE
It loooks like this problem appears only in Chrome. In IE 11 for example everything is ok
the issue might be that you were making the ajax request from a link, and not preventing the link from being followed. So if you are doing this in an onclick attribute, make sure to return false; as well.

Jaspersoft visualise.js report export failing to produce file

I hope there is few among you who have experience with Jaspersoft Reports and their new visualise.js api
I have a problem with visualise.js not producing report export file. What happens is:
I am able to succsefully load the report through the visualise.js API, it loads and displays on my web page
Export controls load up successfully too, so I have dropdown with export file formats and a button to export the file.
When I click the export button though, the whole page reloads as if the export button was really a submit button and nothing happens.
Occasionally, the export will work and it will produce file. Though there is no pattern to when it will produce the file and when it will fail.
Below is the code I am using for this (I am using plain text auth for testing purposes):
visualize({
auth: {
name: "mylogin",
password: "mypass",
organization: "organization_1"
}
}, function (v) {
var $select = buildControl("Export to: ", v.report.exportFormats),
$button = $("#button"),
report = v.report({
resource: "/FPSReports/journal",
container: "#export",
params: {
"journal_ref": [ "<?php echo $reference; ?>" ],
},
success: function () {
button.removeAttribute("disabled");
},
error : function (error) {
console.log(error);
}
});
$button.click(function () {
console.log($select.val());
report.export({
// export options here
outputFormat: $select.val(),
// exports all pages if not specified
// pages: "1-2"
}, function (link) {
var url = link.href ? link.href : link;
window.location.href = url;
}, function (error) {
console.log(error);
});
});
function buildControl(name, options){
function buildOptions(options) {
var template = "<option>{value}</option>";
return options.reduce(function (memo, option) {
return memo + template.replace("{value}", option);
}, "")
}
var template = "<label>{label}</label><select>{options}</select><br />",
content = template.replace("{label}", name)
.replace("{options}", buildOptions(options));
var $control = $(content);
$control.insertBefore($("#button"));
//return select
return $($control[1]);
}
});
HTML:
<div class="grid">
<div class="grid-8"></div>
<div class="grid-8 center">Export</div>
<div class="grid-8"></div>
</div>
<div class="grid">
<div class="grid-24" id="export"></div>
</div>
The only parameter comes from URI segment (I am using codeigniter framework):
$reference = $this->uri->segment(3, 0);
I have found an answer that seems to work, and has resolved the issue. Posting it here in case anyone else has this specific problem like I did.
In brief:
After spending hours looking at console debug output I have realised that each time I tried to send a request for export a new session would be opened. Without logging out of the previous one. And apparently that is a no-no. I do not know JS very well but from what I understood there was session id mismatch in request. Please feel free to correct me here :)
The solution to this problem (or for example if you are having authentication issues with visualize.js) is very simple. Set the authentication in global config:
visualize.config({
auth: {
name: "superuser",
password: "superuser"
}
});
No matter if you are using tokens or plain text or whatever else auth is available through the api.
Then do your stuff wherever else on your website:
visualize(function (v) {
v("#container1").report({
resource: "/public/Samples/Reports/06g.ProfitDetailReport",
error: function (err) {
alert(err.message);
}
});
});
visualize(function (v) {
v("#container2").report({
resource: "/public/Samples/Reports/State_Performance",
error: function (err) {
alert(err.message);
}
});
});
Everything should work for you as it did for me. This works in version 5.6 and 6.1 of visualize.js.
Further reading and links from my research:
Token based authentication to Jasper reports failing when used with visualize.js
Visualize.js authentication error after second login
http://community.jaspersoft.com/questions/842695/visualizejs-authentication-error
http://community.jaspersoft.com/questions/845886/authentication-error-refresh-credentials-visualizejs
Code example (5.6):
http://jsfiddle.net/TIBCO_JS_Community/sozzq0sL/embedded/
Api samples (6.1):
http://community.jaspersoft.com/wiki/visualizejs-api-samples-v61
Api samples (5.6):
http://community.jaspersoft.com/wiki/visualizejs-api-notes-and-samples-v56
Really hope this will help someone new to Jaspersoft & visualize.js like me.

Posting picture to facebook Graph API using angularjs

I try to get the image upload to facebook working... Unfortunately, the facebook graph API always returns the following error:
{ error: Objectcode: 324, message: "(#324) Requires upload file", type: "OAuthException" }
It seems that the picture data is not transfered correctly. The facebook docs tell me to use a multipart/form-data upload. (See here > Publishing)
I am using angular-easyfb as a wrapper for the faceebook sdk. What's the easiest way to get this thing working? My current code is:
var sharePhoto = function() {
ezfb.api("/me/photos",
"POST",
{
"source": content,
"message": "This is a test Photo"
},
function (response) {
console.log("shared", response);
if (response && !response.error) {
/* handle the result */
}
});
};
ezfb.getLoginStatus(function(response) {
if(response.status === 'connected') {
console.log("already conntected", response);
sharePhoto();
} else {
ezfb.login(function(response) {
// Do something with response.
console.log("FB",response);
sharePhoto();
}, {scope: 'public_profile,email,user_photos,publish_actions'});
}
});
The console-log is:
already conntected {status: "connected", authResponse: Object}
shared {error: {code: 324, message: "(#324) Requires upload file", type: "OAuthException"}}
My questions are:
Whats the expected format of my variable content? How do I need to
encode it?
Do I have to manipulate the request Headers of the request? How?
Thanks a lot for your help!
Edit: Console-Log added

Trying to load local JSON file to show data in a html page using JQuery

Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.
<html>
<head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$.getJSON( "priorities.json" , function( result ){
alert(result.start.count);
});
});
</script></head>
</html>
I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
{
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
JSON file name priorities.json and error is
Uncaught Referenceerror priorities is not defined
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
A file can read another file only if the parent directory of the
originating file is an ancestor directory of the target file.
Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert(jsonObject.start.count);
});
</script>
Your priorities.json file:
var jsonObject = {
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
Or declare a callback function on your page and wrap it like jsonp technique:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(e) {
});
function jsonCallback(jsonObject){
alert(jsonObject.start.count);
}
</script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
Your priorities.json file:
jsonCallback({
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
})
Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript
app.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error.
It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
I have Used Following Methods But non of them worked:
// 2 Method Failed
$.get(
'http://www.corsproxy.com/' +
'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
// 3 Method Failed
var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log( "second complete" );
});
// 4 Method Failed
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
success: function(jsondata){
console.log(jsondata)
}
})
// 5 Method Failed
$.ajax({
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' },
dataType: 'jsonp',
/* etc */
success: function(jsondata){
}
})
What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
// Worked After local Web Server
$(document).ready(function () {
$.getJSON('./json/movies-coming-soon.json', function (data) {
var movie_name = '';
var movie_year = '';
$.each(data,function(i,item){
console.log(item.title,item.year,item.poster)
movie_name += item.title + " " + item.year + "<br> <br>"
$('#movie_name').html(movie_name)
})
})
})
Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.
I would try to save my object as .txt file and then fetch it like this:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});

jQuery load() function doesn't load everything [duplicate]

This question already exists:
jQuery .load() function (not loading files completely)
Closed 8 years ago.
I've been strugling with query for some time. I have a CMS that i want to use on my site, buy i cant use PHP includes so i decided to use jquery. I have made all the necesary includes and when i open the webpage it doesn't load all the files... Rarely does load() function load every file. Any ideas to solve the problem or alternatives? thanks.
<script type="text/javascript">
$(document).ready(function(){
// find element with ID of "target" and put file contents into it
$('#welcome-container').load('admin/data/blocks/Slider/Text.html');
$('#slides').load('admin/data/blocks/Slider/Imagini.html');
$('#acasa-continut').load('admin/data/blocks/Acasa/Continut.html');
$('#sidebar').load('admin/data/blocks/Sidebar/Continut.html');
$('#sidebar-v1').load('admin/data/blocks/Sidebar/Video-1.html');
$('#sidebar-v2').load('admin/data/blocks/Sidebar/Video-2.html');
$('#principii').load('admin/data/blocks/Despre/Principii.html');
$('#echipa').load('admin/data/blocks/Despre/Echipa.html');
$('#echipament').load('admin/data/blocks/Despre/Echipament.html');
$('#contact-t').load('admin/data/blocks/Contact/Contact.html');
});
</script>
I have checked with deloper tools and it gives ,randomly on every refresh, 500 Internal Server Error on different elements
Client-side code to request composite HTML and distribute it to the various containers will be something like this :
$(document).ready(function(){
$.ajax({
url: 'admin/data/blocks/all/page.html',
dataType: 'json',
success: function(data){
$.each(data, function(i, obj) {
$('#'+obj.target).html(obj.html);
});
}
});
});
This assumes admin/data/blocks/all/page.html to be a server-side resource that will deliver a json-encoded response of the following construction :
[
{ 'target':'welcome-container', 'html':'<div>whatever</div>' },
{ 'target':'slides', 'html':'<div>whatever</div>' },
{ 'target':'acasa-continut', 'html':'<div>whatever</div>' },
{ 'target':'sidebar', 'html':'<div>whatever</div>' },
{ 'target':'sidebar-v1', 'html':'<div>whatever</div>' },
{ 'target':'sidebar-v2', 'html':'<div>whatever</div>' },
{ 'target':'principii', 'html':'<div>whatever</div>' },
{ 'target':'echipa', 'html':'<div>whatever</div>' },
{ 'target':'echipament', 'html':'<div>whatever</div>' },
{ 'target':'contact-t', 'html':'<div>whatever</div>' },
]

Categories