Mouse event for download working with dartdevc, but not dart2js - dart

I am trying to use code modeled after https://stackoverflow.com/a/29702251/9885144 to do an HttpRequest, generate a download link from the returned blob, then automatically download it (all after clicking a button). Here is the function that runs when the button is clicked: (the Converter.toDocx() function runs an HttpRequest.postFormData() in the format I need and returns the future.)
getDocx(String qStr, String aStr) {
String totalString = qStr + aStr;
Converter.toDocx(convertURL, totalString).then((HttpRequest req) {
String contentType = req.getResponseHeader("content-type");
print(contentType);
String filename = "download.docx";
AnchorElement downloadLink =
new AnchorElement(href: Url.createObjectUrlFromBlob(req.response));
downloadLink.rel = contentType;
downloadLink.download = filename;
var event = new MouseEvent("click", view: window, cancelable: false);
downloadLink.dispatchEvent(event);
});
}
It works fine (on Chrome, Firefox, and Edge) when I use webdev serve. It also works fine when deployed on my remote server with webdev build --no-release -o build:web. But it does not work if I drop the --no-release option so I assume something is different about how dart2js handles this versus dartdevc. I plan to add a popup window with a "click here if it doesn't download" link as a workaround, but is there a better option or is this a dart2js bug?

Related

Vaadin Flow download code works for Chrome but not for Firefox - How can I support both?

I have the following code to download a file from Vaadin Flow (12.0.7).
exportBtn.addClickListener(e -> {
toDownload = FileUtil.getLatestExport();
(toDownload != null) {
StreamResource resource = new StreamResource(toDownload.getName(),
() -> FileUtil.getInputStreamForFile(toDownload));
Element object = new Element("object");
object.setAttribute("download", true);
object.setAttribute("data", resource);
Input name = new Input();
UI.getCurrent().getElement().appendChild(name.getElement(), object);
}
});
toDownload locates the file which I want to download. If I click the button from Chrome the browser downloads my file if I click the button from Firefox nothing happens. In what way do I need to adjust my code to support Chrome and Firefox?
I used this tutorial as reference.
There is also a workaround for downloads triggered by some action in Vaadin Flow, e.g. you have a button that conditionally shows a dialog before downloading the file:
Anchor hiddenDownloadLink = new Anchor(createYourStreamResource(), "Workaround");
hiddenDownloadLink.setId("DownloadLinkWorkaround_" + System.currentTimeMillis());
hiddenDownloadLink.getElement().setAttribute("style", "display: none");
// TODO: add the link somehwere in your view
UI.getCurrent().getPage().executeJs("document.getElementById('" + hiddenDownloadLink.getId().orElseThrow() + "').click();");
Tested in FF, Chrome and Edge. The workaround simulates a click on an anchor that triggers the download.

open file in new tab without creating local or server copy

I have program which stores crystal reports (in bytes in database) and then gives a list of them to user (MVC5). When user clicks on report's name in the list he should see the report in pdf in new tab. On server side I get data contains binary data and length from db. The question is - how to open this data in new tab and not to download converted file on server or local machine?
You can achieve opening a pdf in new browser tab by using window.open and call your server side method in jquery something like this..
jQuery:
$('.reportName').click(function () {
window.open("../../ControllerName/ActionMethodName, '_blank');
});
Server Side:
public static void ActionMethodName()
{
///Here you got to convert your crystal report to memory stream inorder to pass stream array data inside binary write///
HttpContext.Current.Response.AppendHeader("content-disposition", "inline; filename=*****.pdf");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Expires = -1;
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.BinaryWrite(outStream.ToArray());
}

Get the string from selected text/ highlighted text using JXA

I'm supper new here, either Javascript and JXA, so pardon me if I make some stupid questions. But I'm trying to figure out a way to get the string from the highlighted text using JXA - JavaScript for Automation, for Javascript can be recognized in Automator since Yosemite, I thought I can make something work with these:
window.getSelection in:
function getSelectedText() {
if (window.getSelection) {
txt = window.getSelection();
} else if (window.document.getSelection) {
txt =window.document.getSelection();
} else if (window.document.selection) {
txt = window.document.selection.createRange().text;
}
return txt;
}
This code is not mine, somebody posted this. But I've found out that I can't use window or document here in Automator to make change to Mac OS, so can someone show me how to convert this Javascript code into JXA which Automator can understand?
Thanks a lot!
In general, you can use the System Events app to copy and paste with any app.
'use strict';
//--- GET A REF TO CURRENT APP WITH STD ADDITONS ---
var app = Application.currentApplication()
app.includeStandardAdditions = true
var seApp = Application('System Events')
//--- Set the Clipboard so we can test for no selection ---
app.setTheClipboardTo("[NONE]")
//--- Activate the App to COPY the Selection ---
var safariApp = Application("Safari")
safariApp.activate()
delay(0.2) // adjust the delay as needed
//--- Issue the COPY Command ---
seApp.keystroke('c', { using: 'command down' }) // Press ⌘C
delay(0.2) // adjust the delay as needed
//--- Get the Text on the Clipboard ---
var clipStr = app.theClipboard()
console.log(clipStr)
//--- Display Alert if NO Selection was Made ---
if (clipStr === "[NONE]") {
var msgStr = "NO Selection was made"
console.log(msgStr)
app.activate()
app.displayAlert(msgStr)
}
For more info see:
Sending Keystrokes in JXA
JXA Resources
You need to mix JXA and Safari’s javaScript…
var Safari = Application("Safari") // get Safari
selection = Safari.doJavaScript("document.getSelection().toString()",{
in: Safari.windows[0].tabs[0] // assume frontmost window and tab
})
The script is in JXA, but the document.getSelection().toString() is Safari’s javaScript.
Of course you will need to enable apple events in Safari… http://osxdaily.com/2011/11/03/enable-the-develop-menu-in-safari/
If you want the selected text from another application, the code might be very different.
Don't do that, it's only applicable to JavaScript embedded inside a web browser. JXA is a standalone JS interpreter that has absolutely no understanding of web pages or DOM (and frankly doesn't have much clue about Mac application scripting either, btw).
Instead, use Automator to create an OS X Service as services can manipulate selected text in almost any OS X app; no application scripting required.

Getting the current page's window with the low level api of the Firefox SDK

I'm creating a Firefox extension for adding some functionality to certain Web pages. I need to check that some elements do exist and highlight them, so I'm using xpath to check and locate them. I know about manipulating tabs and the content through tabs and ports, but I really need to use the low level API and do it without ports. The thing is, I don't know how to get the current opened tab window (I can also open the tab, but I'm not getting the window). I already tryed to open a tab and :
tabs.open({
url: url,
onOpen: function onOpen(tab) {
// get the XUL tab that corresponds to this high-level tab
var lowLevelTab = viewFor(tab);
var browser = tab_utils.getBrowserForTab(lowLevelTab);
var doc = browser.contentDocument;
console.log(doc); //THIS IS AN EMPTY DOC
// get the most recent window. This give me a XUL window, and I can't sucessfully execute eval on that...
var win = utils.getMostRecentBrowserWindow();
}})
I sawa lot of methods for retrieving different kinds of windows, but I'm not finding the explanation about the differences. E.g. Chroe window, XUL window, NSI window, base window...I just need the current Web page's document window.
Any clarification is welcome.
Thanks in advance,
I just needed to listen for another tab event:
onReady: function onOpen(tab) {
var content = utils.getMostRecentBrowserWindow().content;
var domInstances = content.document.evaluate(me.getTemplateXpath(), content.document, null, 4, null);
var res = domInstances.iterateNext();
while (res) {
console.log(res);
res.style["background-color"] = "orange";
res = domInstances.iterateNext();
}
callback();
}

Open URL with a set Target

EDIT:
The solution I am seeking is a command line to be run to accomplish this from a batch file in Windows.
How would I mimic a browser function to open a URL with a specific target so that if that tab is already open it will load there instead of creating a new tab?
So instead of the default http://url.com with the target "_blank", I could change this to "w00t", etc.
I am using Chrome exclusively, so if this were to be a Chrome specific command, that would be acceptable.
You could create a HTML-page and add the following code like this:
<script>
var url = getQueryVariable("url");
var target = getQueryVariable("target");
window.open(url,target);
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
</script>
I have this script hosted here: scriptcoded.github.io/redirect
You could then call it from a batch-file using this command:
START scriptcoded.github.io/redirect?url=http://www.google.com&target=w00t
Use ?url=http://www.google.com&target=_blank to set the redirect.
The only problems I find with this method is that some browsers blocks the new window and that the tab won't close. Yes, we could use window.close();, but it will only close tabs that were opened by the webpage itself.
Hope it helps!
set name for html tag of target page like this:
<html name="w00t">
Note: A link to URL with target name, sets the name for target window automatically:
Google

Resources