Getting html data from CodeMirror, I get Uncaught ReferenceError: $ is not defined - codemirror

I get my html data from CodeMirror editor using getValue() that includes my jquery library and then the html data is loaded using the following code:
$("newIframe").contents().find("head").html(headDataTag[0]);
$("newIframe").contents().find("body").html(bodyDataTag[0]);
I checked the head and body of the document in the newIframe and the html data seems correct and render the html, javascript code correctly but not the jquery $(document).ready() code section.
Using Opera debugger and clicking on the network tab, it shows jquery downloaded (locally from a node server) correctly with a http status of 200 ok, however, it does not show under the source tab.
This same html data loads without problems using it in a main code without getting the data from CodeMirror editor.
What I'm doing wrong?

I changed the jQuery code just below:
$("newIframe").contents().find("head").html(headDataTag[0]);
$("newIframe").contents().find("body").html(bodyDataTag[0]);
To pure javascript code just below and everything started working:
var iframeId = document.getEelementById("newIframe");
var iframeDoc = iframeId.contentDocument || iframeId.contentWindow.document;
iframeDoc.open();
iframeDoc.write(editor.getValue) // CodeMirror data from it's editor window
iframeDoc.close();

Related

Downloading a PDF from an HTTP POST call

Here is what I'm trying to accomplish (IE 9+, Chrome, FF, Safari) without the use of JQuery:
Make an http POST call to my API endpoint with some data
Server dynamically generates a PDF and returns the PDF as a binary attachment
Browser does default download behavior and downloads the PDF without refreshing the page
Basically I want to get the behavior similar to <a href="test.pdf"> but for a dynamically generated PDF after making a POST call instead of a GET call.
I've tried lots of different things, but they either didn't work cross browser (such as using $window.open() with a blob URL), were blocked by popup blockers (any $window call outside of the click scope), or didn't cause the PDF to be automatically downloaded (any $http POST solution).
I finally found one solution that seems to work which creates a form using javascript and submits it.
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', myurl);
var params = {foo: 'bar'};
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
This successfully accomplishes the 3 steps above, but now I've run into a new problem. There is no way to determine when the PDF file has been successfully downloaded. This is preventing me from removing the form and from displaying a friendly 'Please wait...' message to the user. There is also the additional problem that submitting the form cancels any outstanding ajax requests as well which isn't optimal.
I have full control over both the server and the client, so what's the best way to fix this? I don't want to have to save the PDF on the server so passing back a url and doing a second GET request from the client won't work in this case. Thanks!
You can make an server response behave as a download by applying some HTTP headers:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="SOME_NAME.pdf"
Content-Transfer-Encoding: binary
If you're initiating the download through JS only (instead of having the user click a download link), then check out this question for some caveats.
Update: Syntax for POST
Better Update: Form solution with iframe target
You can detect that your server-side script has finished (and subsequently, that the download is ready to begin) by having the form target an iframe. I believe this should also fix the issue of cancelling outstanding Ajax calls, but I'm not certain. Here is the code to do it (just stick this into your code example after the for loop and before document.body.appendChild(form);):
var frame = document.createElement('iframe');
frame.setAttribute('id', 'pdfFrame');
frame.onload = function(){
document.body.removeChild(form);
document.body.removeChild(frame);
alert('Download ready!');
}
document.body.appendChild(frame);
form.setAttribute('target', 'pdfFrame');
You can replace my alert with your code to remove the 'Please wait...'.

Fetch and display Google Doc body within html page

Is it possible to retrieve the content of a Google Doc and display it within a div in an html page? If so, what's the right way to implement the "MAGIC" in the stripped-down example below?
<html>
<head>
</head>
<body>
<div>
<MAGIC>
Script or link that retrieves and displays the body of a Google Doc.
</MAGIC>
</div>
</body>
</html>
In the above, you can assume
The html is served by Google Drive Hosting.
The reference to the Google Doc is static.
There is no need to edit the Doc from within the public html page (i.e it's read-only in that context).
I've read through the Apps Script documentation and it looks as though something might be possible with some combination of Document Service and Content Service. For instance, Document Service has getBody() and copy() methods, but it's not clear whether the objects returned by these calls can be rendered WYSIWYG as html for insertion into an html container.
Background: I'm trying to implement a safe easy-to-use CMS for a small nonprofit. I've prototyped a website framework that's hosted
on Google Drive. So far it looks promising, but changes require being able to edit the html. We have a number of people who can create content in a word-processor-like environment but only couple including myself
who can cope with HTML/CSS/JQuery/AppsScript.
If I could concentrate on the overall framework and let the others update the content for
events, etc., that would be a huge win. Basically, I'd be very happy if they were able to edit the Google Doc and then manually reload the web page to see the result.
I realize there are many approaches for CMS, but for now, I'm interested in exploring a pure Google Docs/Google Drive solution.
I've settled on publishing the content docs and including the iframe embed code supplied by Google to implement the "MAGIC" from my original question, e.g
<iframe class="cmsframe" src="https://docs.google.com/document/d/1rhkuAB3IIu5Hq0tEtA4E_Qy_-sJMMnb33WBMlAEqlJU/pub?embedded=true"></iframe>
The class tag is added manually so I can control the iframe size with CSS.
You can get the raw html content of a google doc with a call to the drive API using urlFetch, here is how it works
var id = 'Doc-Very-Long-ID-Here';
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
// the variable doc is the HTML content that you can use
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
There is also a library by Romain Vialard available here it is called DocsListExtended and provides a whole bunch of nice extensions.
EDIT : Following your EDIT:
You can't use it just like that, to render an HTML content in a webapp use html service, example below with your complete code and working example:
function doGet() {
var id = '1el3DpTp1sukDjzlKXh8plf0Zj-qm0drI7KbytroVrNU';
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id, googleOAuth_('docs',url)).getContentText();
return HtmlService.createHtmlOutput(doc);
}
// the variable doc is the HTML content that you can use
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}

How do you access Content of an Iframe using GWT?

I have a HiddenIframe that i created in GWT which gets response from a post.
OnBrowsewerevent() i try to introspect the contents of Iframe for a error code or success.
When i access the Iframe via GWT, I can access it but innerHTML method always null
I write a JSNI method
private native String getMessage()/*-{
var e = document.getElementById('my_iframe');
var html = e.contentWindow.document.body.innerHTML;
return html
}-*/;
I always get e as null as GetelementbyID is returning null, When i introspect HTMLusing firebug i can see the Iframe with the ID. What is the best way to solve the problem?
You need to use the GWT specific $doc variable, instead of document. From the GWT JSNI documentation:
When accessing the browser's window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page's window and document.

GWT dynamic data in new browser window at client side

I've got GWT module where I do some stuff and I have search results - doesn't matter in which form. Now after searching, and clicking on for example "Export to HTML" button,I would like to create new html page (for example from client side code by creating simple string which contains only listed results of searching list of results ) and open it in new browser window. I know that there is Window.open(...) method, but there I must specify url which i don't have. I want to create this new html page by client side - without server inference (I don't want to create some resource on server side and then paste url to this resource to client side). Is there any possibility to achieve this? If there is no option, other method which would satisfy me, is to open standard dialog box for saving, which will allow to save results in a html file.
Thanks for helps.
Kind regards.
Here's the code I use to print:
native void openPrintWindow(String contents) /*-{
var printWindow = window.open("", "PrintWin");
if (printWindow && printWindow.top) {
printWindow.document.write(contents);
printWindow.print();
printWindow.close();
} else {
alert("The print feature works by opening a popup window, but our popup window was blocked by your browser. If you can disable the blocker temporarily, you'll be able to print here. Sorry!");
}
}-*/;
Seems like you could adapt it for your purposes with some simple rewording and by removing the call to print()! The contents variable just holds flat HTML. There are no trips to the server.
openPrintWindow("<h1>Search Results</h1><ol><li>etc...");
The method of opening new window from client js which allows user to save that generated content from browser's save as menu is data:url scheme, content written to opened page via println usualy not saved. But data:url works only in morden browsers. And the content written should be quite small to fit browser's url length resteiction.
See example from this article http://en.wikipedia.org/wiki/Data_URI_scheme#JavaScript

Greasemonkey script not executed when unusual content loading is being used

I'm trying to write a Greasemonkey script for Facebook and having some trouble with the funky page/content loading that they do (I don't quite understand this - a lot of the links are actually just changing the GET, but I think they do some kind of server redirect to make the URL look the same to the browser too?). Essentially the only test required is putting a GM_log() on its own in the script. If you click around Facebook, even with facebook.com/* as the pattern, it is often not executed. Is there anything I can do, or is the idea of a "page load" fixed in Greasemonkey, and FB is "tricking" it into not running by using a single URL?
If I try to do some basic content manipulation like this:
GM.log("starting");
var GM_FB=new Object;
GM_FB.birthdays = document.evaluate("//div[#class='UIUpcoming_Item']", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (i = GM_FB.birthdays.snapshotLength - 1; i >= 0; i--) {
if (GM_FB.birthdayRegex.test(GM_FB.birthdays.snapshotItem(i).innerHTML)) {
GM_FB.birthdays.snapshotItem(i).setAttribute('style','font-weight: bold; background: #fffe88');
}
}
The result is that sometimes only a manual page refresh will make it work. Pulling up the Firebug console and forcing the code to run works fine. Note that this isn't due to late loading of certain parts of the DOM: I have adding some code later to wait for the relevant elements and, crucially, the message never gets logged for certain transitions. For example, when I switch from Messages to News Feed and back.
Aren't they using ajax to load content in a div? You can find the element which is being updated by using Firebug for example.
When you click something and the URL changes, but with a # on the URL and after this some text, it means the text is not a path, it's a parameter, the browser won't change the page you are, so since GreaseMonkey inject the script on the page loads it won't inject again, because the page is not reloading.
As in your example the URL facebook.com/#!/sk=messages is not navigating away from facebook.com/ it will not fire window.load event.
So you need to find which element is being changed and add an event listener to that element, you can do is using Firebug as I mentioned before.
After you find out what element is getting the content, you have to add an event listener to that element and not the page (GreaseMonkey adds only on the window load event).
So in you GM script you would have ("air code")
document.getElement('dynamic_div').addEvent('load', /*your script*/);