How to open a url with parameters in external browser with WinJS - javascript

I have a metro app developed with WinJS in VS2012 and I want to open this address
window.location = "http://XXX.XXX.XX.XXX:XXXX/test/AU/jsp/AU000007.jsp";
this works ok, opens the webpage on new browser from my metro app
But I want to add several parameters encrypted by using jcrypto so I do this:
//message encryption
message = jcrypto(message);
message = "http://XXX.XXX.XX.XXX:XXXX/test/AU/jsp/AU000007.jsp?data=" + message;
window.location = message;
but it just opens the link on my metro app, how to fix that???
UPDATE: thanks to WiredPrairie's suggestion I found this answer:
var uri = new Windows.Foundation.Uri("http://XXX.XXX.XX.XXX:XXXX/test/AU/jsp/AU000007.jsp?data=" + jcrypto(message));
//opens the url on external browser
Windows.System.Launcher.launchUriAsync(uri).done(
function (success) {
if (success) { console.log("page opened correctly"); }
else { console.log("an error has occured"); }
});

try with this other:
//message encryption and URL addition
message = "http://XXX.XXX.XX.XXX:XXXX/test/AU/jsp/AU000007.jsp?data=" + jcrypto(message);
window.open(message, "_blank", "fullscreen=yes,height=600,width=800,scrollbars=yes,resizable=no");

Related

Saving a file in a UWP web context

I recently developed a universal application for Windows 10 with UWP web context (so JavaScript and HTML) and I would like to save a text file. It works well on a browser (Chrome, Firefox, Edge,...) but not in the application.
Can someone help me? :)
Thank you in advance!
Here is the code responsible for saving the text file.
function saveTextAsFile(fileName) {
var source = input.value.replace(/\n/g, "\r\n");
var fileUrl = window.URL.createObjectURL(new Blob([source], {type:"text/plain"}));
var downloadLink = createDownloadLink(fileUrl, fileName);
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);}
To download a file using a Progressive Web App as a Universal Windows Platform you can use the Windows global object with the FileSavePicker. Note that you can check to see if it exists using if (window['Windows'] != null) { ... }
// Create the picker object and set options
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
// Default file name if the user does not type one in or select a file to replace
savePicker.suggestedFileName = "New Document";
savePicker.pickSaveFileAsync().then(function (file) {
if (file) {
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.deferUpdates(file);
// write to file
Windows.Storage.FileIO.writeTextAsync(file, fileContents).done(function () {
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status");
} else {
WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status");
}
});
});
} else {
WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
}
});
This assumes you are downloading a text file. To download a Uint8Array use the WriteBytesAsync function on FileIO instead. Note that many of the functions on FileIO are available in JavaScript even though they are not documented for JavaScript.
Check out the FileSavePicker Class documentation for more information.

WebRTC issue with File transfer in production application

Hello I am developing a WebRTC based file transfer application.I have deployed the application online using Heroku. But there seems to be a problem with file transfer specifically at the the receiving end which I have been unable to figure out. The file is transferred and received successfully when done on localhost but there is a problem with file reception when done in production. The browser used is Google Chrome if that's any help.
Here is the File reception code:
function dataChannelStateChanged() {
if (dataChannel.readyState === 'open') {
console.log("Data Channel open");
dataChannel.onmessage = receiveDataChannelMessage;
}
}
function receiveDataChannel(event) {
console.log("Receiving a data channel");
dataChannel = event.channel;
dataChannel.onmessage = receiveDataChannelMessage;
}
function receiveDataChannelMessage(event) {
console.log("From DataChannel: " + event.data);
if (fileTransferring) {
//Now here is the file handling code:
fileBuffer.push(event.data);
fileSize += event.data.byteLength;
fileProgress.value = fileSize;
//Provide link to downloadable file when complete
if (fileSize === receivedFileSize) {
var received = new window.Blob(fileBuffer);
fileBuffer = [];
downloadLink.href = URL.createObjectURL(received);
downloadLink.download = receivedFileName;
downloadLink.appendChild(document.createTextNode(receivedFileName + "(" + fileSize + ") bytes"));
fileTransferring = false;
//Also put the file in the text chat area
var linkTag = document.createElement('a');
linkTag.href = URL.createObjectURL(received);
linkTag.download = receivedFileName;
linkTag.appendChild(document.createTextNode(receivedFileName));
var div = document.createElement('div');
div.className = 'message-out';
div.appendChild(linkTag);
messageHolder.appendChild(div);
}
}
else {
appendChatMessage(event.data, 'message-out');
}
}
The following image shows the problem i'm encountering when receiving the file:
Any guidance would be much appreciated.
WEBRTC is based on UDP, it means there is no guarantee that your sequence of data transfers "in order" or successfully
use "webSocket" or a simple "http request" instead.
=============
UPDATE: see the first comment

opentok.js error when stopping screensharing (Cannot read property 'connections' of null)

I am trying to implement screen sharing using TokBox service in chrome and chromium.
After chrome prompts to select a window everything works correctly but when I stop the screen sharing clicking on the "Stop sharing" button in the "pop up" that appears when screen sharing is in progress an error occurs:
Uncaught TypeError: Cannot read property 'connections' of null ---- opentok.js line 11103
When using tokbox meet demo in the same browser this error does not happen: http://meet.tokbox.com
I modified the basic tokbox tutorial code to reproduce this problem:
<div id="camera"></div>
<div id="screen-preview"></div>
<div id="screen"></div>
<script src="//static.opentok.com/v2/js/opentok.js"></script>
<script type="text/javascript">
// Go to https://dashboard.tokbox.com/ to find your OpenTok
// API key and generate a test session ID and token:
var apiKey = "<%= api_key %>";
var sessionId = "<%= session_id %>";
var token = "<%= token %>";
var session = OT.initSession(apiKey, sessionId);
session.connect(token, function(error) {
var publisher = OT.initPublisher('camera');
session.publish(publisher);
screenshare();
});
session.on('streamCreated', function(event) {
session.subscribe(event.stream, 'screen');
});
// For Google Chrome only, register your extension by ID. You can
// find it at chrome://extensions once the extension is installed.
OT.registerScreenSharingExtension('chrome', '<%= chrome_extension_id %>');
function screenshare() {
OT.checkScreenSharingCapability(function(response) {
if (!response.supported || response.extensionRegistered === false) {
alert('This browser does not support screen sharing.');
} else if (response.extensionInstalled === false) {
alert('Please install the screen sharing extension and load your app over https.');
} else {
// Screen sharing is available. Publish the screen.
var screenSharingPublisher = OT.initPublisher(
'screen-preview',
{videoSource : 'screen'},
function(error) {
if (error) {
alert('Something went wrong: ' + error.message);
} else {
session.publish(
screenSharingPublisher,
function(error) {
if (error) {
alert('Something went wrong: ' + error.message);
}
});
}
});
}
});
}
</script>

How do I save user email as a variable when someone installs the extension?

In my bookmarking extension, I need to send the gmail address of the user to google app engine in order to write the bookmark to the database as the user as "owner".
My understanding is that I cannot use a popup because I have a background page (I remember reading about this but I could not find it again). I am also reading the installation process in Chrome store. I would appreciate if anyone can direct me to the right place in the documentation.
I copy my background.html below with the variable extension_user included. How do I get this variable from the user when they upload the extension? This is my previous question.
<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
var firstParagraph = response.dom;
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
//***the variable with user email to send to backend:***//
//formData.append("extension_user", extension_user)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}else{
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
}
}
};
xhr.send(formData);
}); //chrome.tabs.sendRequest
});
});
</script>
</html>
You can use both a popup and background page in a single extension. A lot of my extensions use both... Use the background page to communicate and save data for your popup page...
You can prompt your user to save their email address on install in your background page as follows:
<script type="text/javascript">
addEventListener('load', function(){
var MAJOR_VERSION=1.0;
if(!localStorage.updateread||localStorage.updateread!=MAJOR_VERSION)
{
var email=prompt("Enter the Email Address : ")
localStorage["Email"] = Email;
localStorage.updateread=MAJOR_VERSION
}
}, 0);
</script>
This script will only run when you first install the extension. And the users email address will be saved in the extensions LocalStorage until they uninstall... Calling this variable will now work in both your background page and your popup page...

Download images and save locally on iPhone Phonegap app

I've already managed to save a web page (x/html) successfully, but I'd also like to save the images and mp4 videos that are contained in it, for further visualization in offline mode.
I've got access to the iOS filesystem, so I save the html by obtaining the code through an AJAX request, and later saving it to a file.
I don't really know how to do the same with video and images. I have a server to which I can send queries from my app, so it shows exclusively the content I need to download, with the optimal headers in case its necessary. I just don't know how to "download" it from the client side (Javascript).
Thanks in advance for any help.
You can use a FileTransfer object to download a remote image to a local file.
This is the latest official sample snippet:
// !! Assumes filePath is a valid path on the device
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");
fileTransfer.download(
uri,
filePath,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
You can only do it natively I'm afraid.
I'm doing it through a FileDownload PhoneGap Plugin that I wrote, using NSURLConnection. I pass in the url to download to the plugin through Javascript, and a target location (and it even gives me download progress).
Have not tested it yet, but the documentation at PhoneGap looks quite promising http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html
I have used this snippet on my ios app project:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
var target_directory="";
function fail() {
//alert("failed to get filesystem");
}
function downloadImage(url, filename){
alert("download just started.");
try{
var ft = new FileTransfer();
ft.download(
url,
target_directory + filename,
function(entry) {
//alert("download complete!:" + entry.nativeURL ); //path of the downloaded file
},
function(error) {
//alert("download error" + error.code);
//alert("download error" + JSON.stringify(error));
}
);
}
catch (e){
//alert(JSON.stringify(e));
}
}
function success(fileSystem) {
target_directory = fileSystem.root.nativeURL; //root path
downloadImage(encodeURI("http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg"), "cat.jpg"); // I just used a sample url and filename
}

Categories

Resources