How to enable folders in Chrome devtools > Sources > Page > top > (no domain) (files with //# sourceURL=...) - google-chrome-devtools

Is there a way to show folders for path's in Chrome devtool > Page panel
for tree nodes in top > (no domain)
these are node comming from js eval with a //# sourceURL=...
as my code contains a lot of these I want them to show as
- top
- MyDomain
- MyFile
- (no domain)
- FolderA
- Eval1
- Eval2
- FolderB
- Eval3
- Eval4
Instead of
- top
- MyDomain
- MyFile
- (no domain)
- FolderA/Eval1
- FolderA/Eval2
- FolderB/Eval3
- FolderB/Eval4

Include the domain (origin) in the sourceUrl.
I had to find this out by trial and error, it is not well-documented anywhere.
JS syntax:
//# sourceURL=http://mySite:8000/FolderA/File1.js
Css syntax:
/*# sourceURL=http://mySite:8000/FolderA/File1.css */
Build it in the browser:
Create a sourceUrl from a relative url:
function jsSrcUrl(path) {
return "//# sourceURL=" + window.origin + path + " \n";
}
var src = "/js/myScript.js"; // use this url in your GET request via fetch()
var sourceUrl = jsSrcUrl(src); // append this and eval it later
Create a sourceUrl during a fetch request:
var src = "/ui/vue.js";
var fullUrl;
fetch(src)
.then(function(response) {
fullUrl = response.url;
return response.text()
})
.then(function(text) {
console.log(text)
})
var sourceUrl = "//# sourceURL=" + fullUrl + " \n"
Add a sourceUrl to your script (which is a string before eval):
var scriptWithSrcUrl = script.concat(sourceUrl);
Eval your script to load your script (string) into the browser and sources panel
eval(scriptWithSrcUrl)
Put it all together: Create a sourceUrl during a fetch request AND append it to the script AND eval it:
async function loadScript(url) {
var fullUrl;
async function getScript() {
return fetch(url)
.then(function(response) {
fullUrl = response.url;
return response.text();
})
.then(function(text) {
return text;
});
}
var script = await getScript();
var sourceUrl = "\n//# sourceURL=" + fullUrl + " \n";
var scriptWithSrcUrl = script.concat(sourceUrl);
(1, eval)(scriptWithSrcUrl);
}
loadScript("/path/to/script.js");
Look in your devtools sources panel and find your file in the proper folder and domain!
Dear Google, Mozilla, Microsoft, & Apple:
The fetch api is nice, but fetching js/css/html via a get request, injecting a sourceUrl, and eval'ing it is not just lame, it's ultra lame. Loading everything in a script tag in the document head doesn't play nice with lazy-loading components, code-splitting, tree shaking, and SSR in general. Wouldn't it be nice if there was an api to load js, css, html templates, components, and js modules into global scope - all from js (not from html) natively using browser api's?
A way that doesn't involve:
ES6 module syntax and scope (for loading into local scope)
fetch() + sourceUrl + eval()
document.createElement('script') + set src + onload() (pollutes the doc head)
Some library/dependency (Jquery $.getScript(), Fetch inject, Requirejs, etc.)
I am sure that this api already exists within the browser, script tags probably already consume that js api...can't we just have nice things?
loadScript("path/to/js.js"); // for loading js into global scope
Such a simple use case, yet no API.

Related

Using Sailsjs Skipper file uploading with Flowjs

I'm trying to use skipper and flowjs with ng-flow together for big file uploading.
Based on sample for Nodejs located in flowjs repository, I've created my sails controller and service to handle file uploads. When I uploading a small file it's works fine, but if I try to upload bigger file (e.g. video of 200 Mb) I'm receiving errors (listed below) and array req.file('file')._files is empty. Intersting fact that it happening only few times during uploading. For example, if flowjs cut the file for 150 chunks, in sails console these errors will appear only 3-5 times. So, almost all chunks will uploaded to the server, but a few are lost and in result file is corrupted.
verbose: Unable to expose body parameter `flowChunkNumber` in streaming upload! Client tried to send a text parameter (flowChunkNumber) after one or more files had already been sent. Make sure you always send text params first, then your files.
These errors appears for all flowjs parameters.
I know about that text parameters must be sent first for correct work with skipper. And in chrome network console I've checked that flowjs sends this data in a correct order.
Any suggestions?
Controller method
upload: function (req, res) {
flow.post(req, function (status, filename, original_filename, identifier) {
sails.log.debug('Flow: POST', status, original_filename, identifier);
res.status(status).send();
});
}
Service post method
$.post = function(req, callback) {
var fields = req.body;
var file = req.file($.fileParameterName);
if (!file || !file._files.length) {
console.log('no file', req);
file.upload(function() {});
}
var stream = file._files[0].stream;
var chunkNumber = fields.flowChunkNumber;
var chunkSize = fields.flowChunkSize;
var totalSize = fields.flowTotalSize;
var identifier = cleanIdentifier(fields.flowIdentifier);
var filename = fields.flowFilename;
if (file._files.length === 0 || !stream.byteCount)
{
callback('invalid_flow_request', null, null, null);
return;
}
var original_filename = stream.filename;
var validation = validateRequest(chunkNumber, chunkSize, totalSize, identifier, filename, stream.byteCount);
if (validation == 'valid')
{
var chunkFilename = getChunkFilename(chunkNumber, identifier);
// Save the chunk by skipper file upload api
file.upload({saveAs:chunkFilename},function(err, uploadedFiles){
// Do we have all the chunks?
var currentTestChunk = 1;
var numberOfChunks = Math.max(Math.floor(totalSize / (chunkSize * 1.0)), 1);
var testChunkExists = function()
{
fs.exists(getChunkFilename(currentTestChunk, identifier), function(exists)
{
if (exists)
{
currentTestChunk++;
if (currentTestChunk > numberOfChunks)
{
callback('done', filename, original_filename, identifier);
} else {
// Recursion
testChunkExists();
}
} else {
callback('partly_done', filename, original_filename, identifier);
}
});
};
testChunkExists();
});
} else {
callback(validation, filename, original_filename, identifier);
}};
Edit
Found solution to set flowjs property maxChunkRetries: 5, because by default it's 0.
On the server side, if req.file('file')._files is empty I'm throwing not permanent(in context of flowjs) error.
So, it's solves my problem, but question why it behave like this is still open. Sample code for flowjs and Nodejs uses connect-multiparty and has no any additional error handling code, so it's most likely skipper bodyparser bug.

is there possible calling gwt jsni method with chrome extension using chrome.tab.executeScript?

I have a gwt project that wrap in chrome extensions.
In GWT, I export a java method to jsni called:
Java Method: sendMessage(String msg);
export jsni: $wnd.sendMessage = function(msg) { ... };
then in chrome extension, I execute:
chrome.tabs.executeScript(tabId, {code: "sendMessage('hello');"}
but not thing happened, I've tried:
chrome.tabs.executeScript(tabId, {code: "alert('hello');"}
and it just works fine. but it just can't call my gwt jsni method.
Chrome content scripts exist in an isolated world.
$wnd.sendMessage is exported in the page context, and not accessible from a content script.
You'll need to inject code into the page itself (with a <script> tag) to access it.
See this canonical question on the topic, and this question can also be of use: Executing code at page-level from Background.js and returning the value
solved the problem, when pass a json string, you have to encode the string to prevent double quotes/special character in the string, here is my code:
assume the data format is:
var data = '{"abc":123,"cde":"kkk"}';
then encode the data:
var param = '\'' + encodeURIComponent(data) + '\'';
put then data into the code to execute:
var codeToExec = [
'var actualCode = "window.sendMessage(' + param + ');"',
'var script = document.createElement("script");',
'script.textContent = actualCode;',
'(document.head||document.documentElement).appendChild(script);',
'script.remove();'
].join('\n');
chrome.tabs.executeScript(mainTabId, {code: codeToExec});

hello, is there a way for consuming a Rest service in an app for windows 8.1 using WinJS?

hello I'm trying to consume a REST service in an app for windows 8.1, I'm so gratefull if you can give me more information related about this topic, thanks !!
You could use the XMLHttpRequest object. But, since you are using WinsJS, the WinJS.xhr function would be more convenient.
Here's an example on how to use it:
(function () {
"use strict";
var app = WinJS.Application;
app.onactivated = function (args) {
// Change RSS feed URL as you need to.
var resDiv = document.getElementById("divResult"),
rssURL = "http://blogs.windows.com/windows/b/appbuilder/rss.aspx";
// Call WinJS.xhr to retrieve an XML feed from the Web.
WinJS.xhr({
url: rssURL,
responseType: "document"
}).done(
// When the result has completed, check the status.
function completed(result) {
if (result.status === 200) {
// Get the XML document from the results.
var xmlDocument = result.responseXML,
title = xmlDocument.getElementsByTagName('title')[0];
// Update the HTML in the app.
resDiv.style.backgroundColor = "lightGreen";
resDiv.innerText = "Downloaded RSS feed from the " + title.textContent + " blog.";
}
});
};
app.start();
})();

How to play secure streamed url of asset fetched dynamically through code( In Azure media services)

I am using Azure Media Services and a Silverlight Player to play the streamed url
I am able to ingest, encode the video file as an asset file but when I go play the streamed url I am facing problem.
I use following code to fetch the url...
context = new CloudMediaContext(_accountName, _accountKey);
IAsset myAsset = GetAsset("UUID:7a32b941-30bd-4c96-bf4e-26df5022eec5");
var theManifest = from f in myAsset.AssetFiles
where f.Name.EndsWith(".ism")
select f;
var manifestFile = theManifest.First();
IAccessPolicy streamingPolicy = _context.AccessPolicies.Create("Streaming policy",
TimeSpan.FromDays(10),
AccessPermissions.Read);
ILocator originLocator = _context.Locators.CreateSasLocator(myAsset, streamingPolicy, DateTime.UtcNow.AddMinutes(-500));
GetAssetSasUrlList(myAsset, originLocator);
string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest";
Console.WriteLine("URL to manifest for client streaming: ");
Console.WriteLine(urlForClientStreaming);
this url comes like --
https://mediasvc06w4dq5k8vd08.blob.core.windows.net/asset-064ed2d5-e42d-4c49-98eb-a712db5c614f?st=2012-12-26T23%3A04%3A22Z&se=2013-01-05T23%3A04%3A22Z&sr=c&si=9350bd2f-ec23-40b2-b27a-248bba01b97e&sig=oGgesnr8mXjCdTM5Dz%2FQpFRBDR0g0%2F60ECoXY14EvsA%3DBigBuckBunny.ism/manifest
Its not working .
When I paste this url on browser directly ,I get following error
AuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:154422cf-822e-4bbc-af2a-fa69273dfb89 Time:2012-12-27T08:57:30.9509847ZSignature fields not well formed.
But if I go and publish asset from portal( www.manage.windowsazure.com )--
I get like following url on protal..
http://mediaervices.origin.mediaservices.windows.net/5edbeae7-c3e6-45c5-bc5c-70f46b526cb5/BigBuckBunny.ism/Manifest
And it works with my silverlight player..
Now problem is that I am not getting url which starts with http from code and the url starting with https is not working with my player.
I guessed that its security issue and tried to host my player in winows azure and tried to player there but no success.
No, not a security issue. You are requesting a SAS url for a Smooth asset, you need an Origin URL. The correct code snippet is here, on my blog:
http://blog-ndrouin.azurewebsites.net/?p=1931
Specifically:
private static string GetStreamingUrl(CloudMediaContext context, string outputAssetId)
{
var daysForWhichStreamingUrlIsActive = 365;
var outputAsset = context.Assets.Where(a => a.Id == outputAssetId).FirstOrDefault();
var accessPolicy = context.AccessPolicies.Create(outputAsset.Name, TimeSpan.FromDays(daysForWhichStreamingUrlIsActive), AccessPermissions.Read | AccessPermissions.List);
var assetFiles = outputAsset.AssetFiles.ToList();
var assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith("m3u8-aapl.ism")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, accessPolicy);
Uri hlsUri = new Uri(locator.Path + assetFile.Name + "/manifest(format=m3u8-aapl)");
return hlsUri.ToString();
}
assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, accessPolicy);
Uri smoothUri = new Uri(locator.Path + assetFile.Name + "/manifest");
return smoothUri.ToString();
}
assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith(".mp4")).FirstOrDefault();
if (assetFile != null)
{
var locator = context.Locators.CreateLocator(LocatorType.Sas, outputAsset, accessPolicy);
var mp4Uri = new UriBuilder(locator.Path);
mp4Uri.Path += "/" + assetFile.Name;
return mp4Uri.ToString();
}
return string.Empty;
}

How can I fix this CouchDB rewrite handler's infinite loop?

If I don't use a rewrite in my CouchDB app, my static file links break:
GET http://127.0.0.1:5984/mythshare-dev/_design/mythshare/_rewrite/static/js/jquery-1.7.1.min.js 404 (Object Not Found)
GET http://127.0.0.1:5984/mythshare-dev/_design/mythshare/_rewrite/static/js/json2.js 404 (Object Not Found)
GET http://127.0.0.1:5984/mythshare-dev/_design/mythshare/_rewrite/static/style/example.css 404 (Object Not Found)
modules.js:4264Uncaught ReferenceError: $ is not defined
So I added this rewrite to fix the broken links:
{from: '/static/*', to: 'static/*'}
My broken links are fixed, but the handler doesn't work properly. modules.js's handle function doesn't match...
exports.handle = function (method, url, data) {
if (exports.unknown_target) {
window.location = exports.getBaseURL() + url;
return;
}
// match resolves to FALSE
var match = exports.matchURL(method, url);
...
Which leads to this:
...
else {
// this log is written over and over in the console
console.log(method + ' ' + url + ' -> [404]');
window.location = exports.getBaseURL() + url;
return;
}
The page now constantly refreshes, caught in an infinite loop.
How can I write the rewrite to the static directory so it resolves properly and matches?
Remove the script tag for modules.js in the base.html template.