The following line of code works but returns the HTML code before executing the java scripts in the page.
var myContent = String(contentsOfURL: NSURL(string: myURL)!, encoding: NSUTF8StringEncoding, error: nil) as String!
I've been researching this for a while but I'm having a hard time filtering out all the iOS noise (any advise on this would be highly appreciated).
JavaScript code embedded in HTML is meant to be executed by a rendering engine such as a browser. when you download a HTML file (using String(contentsOfURL...)) you are doing exactly that - downloading the HTML file. There is no execution.
Once you download the file, you can then render the HTML file (for example, by loading it in a UIWebView - see How to load local html file into UIWebView for an example). Rendering the HTML file will "execute" the JavaScript based on how the HTML+JavaScript is authored.
Related
I can't find syntax errors in my JavaScript that is in the Google HTMLService (html window in Google Scripts). My work involves Google Visualizations which requires this. It is my first experience with JavaScript and HTML so I'm quite prone to mistakes making this a distressing problem.
The execution log just shows that the html was run, and I don't where in my code to look for errors. I expect that somewhere would say "error in: line x" or "object not accepted line y" but I just don't know where to look.
I would appreciate any pointers on where to find a solution or how to clarify my question.
You can use your browser's Developers Tools. In Chrome, press the f12 button, OR choose More Tools, Developer Tools, and window will open in your browser that looks like this:
One of the tabs is labeled Console. You can print information to the console by using a:
console.log('This is text: ' + myVariable);
statement.
When the Apps Script macro runs, and serves the HTML to your browser, if there are errors, they will be displayed in the Console Log.
I used the HTML you posted, and got msgs in the console of this:
So, for the JavaScript in a <script> tag of the HTML, you don't look for errors in the Apps Script code editor. You need to use the browsers Developer Tools. The JavaScript in a .gs code file is server side code. It runs on Google's servers. The JavaScript in an HTML tag runs in the users browser on the users computer.
You can also step through client side JavaScript code in your browser.
One problem is, that when the HTML is served, the code is changed.
So the JavaScript in your Apps Script code editor will not look the same as what gets served to the browser. If you view the JavaScript served to the browser, it will look totally different than the code in the Script tag in the original file.
You could also use a code editor that has error checking in it. Net Beans has a free code editor.
Debugging a Google Apps Script web application depends a lot on what Google Apps Script features are used, i.e. if it's created using templated HTML, if the client side communicates with the server side, etc.
As the OP case the Google Apps Script execution log doesn't show any error message, it's very likely that the HtmlOutput was created and it should be possible to inspect the code on the client-side.
Google sends to the client-side a IIFE that inserts into an iframe a satinized version of the HTML/CSS/JavaScript passed to the HtmlService, i.e. the white spacing will not be same, comments will not be included among other changes. Anyway, you might use the dev tools to see the resulting JavaScript and call JavaScript functions from dev tools console, etc.
To execute client-side JavaScript from a Google Apps Script web app, first select the userHtmlFrame(userCodeAppPanel) on the console dropdown selector:
You can even do changes to the client-side JavaScript using the dev tools Elements panel or using JavaScript in the dev tools console, and do other stuff. Just bear in mind that changes done there will not be saved on the Google Apps Script project.
It's worthy to mention that it's possible to debug pure JavaScript using the Google Apps Script editor. The easier way is to put the JavaScript code in a .gs file and use HtmlTemplate to create the HtmlOutput object of the web application together with: ScriptApp.getResource(name).getDataAsString(). Also this approach will help to test the JavaScript code using desktop tools, will help to make it easier to fix "Malformed" errors caused by missing / misplaced <,>,",',(,),:,; and take advantage of the intellisense features for JavaScript that aren't available in the .html files.
Sample of a web application having the client-side JavaScript on a .gs file instead of on a .html file. The client-side JavaScript is in the javascript.js.gs file. In this overly simplified example, the function to be tested require parameters. This makes that the function cannot be run directly from the Editor toolbar, so there is couple of "test" functions on the test.gs file that set the required parameters and call the function that we want to debug.
Code.gs
/**
* Respond to HTTP GET request. Returns a htmlOutput object.
*/
function doGet(e){
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('My web app');
}
/**
* Returns the file content of a .gs or .html Google Apps Script file.
*
* #param {filename} Google Apps Script file name. It should not include the .gs or .html file extension
*/
function include(filename){
const [name, sufix] = filename.split('.');
switch(sufix){
default:
return HtmlService.createHtmlOutputFromFile(name).getContent();
case 'js':
const content = ScriptApp.getResource(name).getDataAsString();
return `<script>${content}</script>`;
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<?!= include('stylesheet.css') ?>
</head>
<body>
<p>Add here some content</p>
<?!= include('javascript.js') ?>
</body>
</html>
javascript.js.gs
/**
* Arithmetic addition of two operands. Validates that both operands are JavaScript numbers.
*
* #param {number} a Left addition operand
* #param {number} a Right addition operand
*/
function addition(a,b){
if(typeof a !== 'number') || typeof b !== 'number') throw new Error('Operands should be numbers');
return a + b;
}
tests.gs
/**
* Passing two numbers. Expected result: 2.
*/
function test_addition_01(){
const a = 1;
const b = 1;
const result = addition(a,b);
console.log(result === 2 ? 'PASS' : 'FAIL');
}
/**
* Passing one number and one string. Expected result: Custom error message.
*/
function test_addition_02(){
const a = 1;
const b = '1';
try{
const result = addition(a,b);
} catch(error) {
console.log(error.message === 'Operands should be numbers' ? 'PASS' : 'FAIL');
}
}
Note: ScriptApp.getResource can't pull files from libraries even when including this method on the library
For debugging JavaScript that makes use of other technologies, i.e. document.getElementById(id) one option is to dev tools console or using try... catch and call some function from the server side, google.script.run, for logging errors on the execution logs.
To debug a JavaScript that calls JavaSCript libraries, you might copy the libraries code into one or multiple .gs files or load it into the server side by using UrlFetchApp and eval (see How to load javascript from external source and execute it in Google Apps Script)
I compiled my reactjs using webpack and got a bundle file bundles.js. My bundles.js contains a component that make API calls to get the data.
I put this file in my html and pass the url to phantom.js to pre-compile static html for SEO reasons.
I am witnessing something strange here, the ajax calls for APIS are not getting fired at all.
For example, I have a component called Home which is called when I request for url /home. My Home component makes an ajax request to backend (django-rest) to get some data. Now when I call home page in phantomjs this api call is not getting fired.
Am I missing something here?
I have been using React based app rendering in Phantomjs since 2014. Make sure you use the latest Phantomjs version v2.x. The problems with Phantomjs occur because it uses older webkit engine, so if you have some CSS3 features used make sure they are prefixed correctly example flexbox layout.
From the JS side the PhantomJS does not support many newer APIs (example fetch etc.), to fix this add the polyfills and your fine. The most complicated thing is to track down errors, use the console.log and evaluate code inside the Phantomjs. There is also debugging mode which is actually quite difficult to use, but this could help you track down complex errors. I used webkit engine based browser Aurora to track down some of the issues.
For debugging the network traffic, try logging the requested and received events:
var page = require('webpage').create();
page.onResourceRequested = function(request) {
console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
We are developing an GWT web-application with an Python webapp2 webserver. At this point we want to load and save files within the web-application. We cannot use Flash for this task.
Saving
The current approach is to use a form upload using the target "_blank" and set the correct MIME to make the browser download the file. This solution works, but since the webapp2 webserver does not support streaming (thus the mime type cannot be validated by the browser in a short time), a new browser-window is opened each time. Is there a better solution e.g. using iFrames?
Loading
Again using form upload and parsing the response (JSON). We use the content-type "text/html; charset=UTF-8". This solution works perfectly in IE9 but does not work in Chrome and FireFox. It seems, that the JSON response gets corrupted in some way or is there anything from when parsing a JSON response from a form upload response? We use piriti for JSON (de)serialization.
For loading, you can use RestyGWT library, it has capability encoding or decoding Java Object to JSON:
import javax.ws.rs.POST;
...
public interface PizzaOrderCodec extends JsonEncoderDecoder<PizzaOrder> {
}
// GWT will implement the interface for you
PizzaOrderCodec codec = GWT.create(PizzaOrderCodec.class);
// Encoding an object to json
PizzaOrder order = ...
JSONValue json = codec.encode(order);
// decoding an object to from json
PizzaOrder other = codec.decode(json);
For saving, if you have to send JSON file using file upload, you can see following link:
http://www.jroller.com/hasant/entry/fileupload_with_gwt
http://www.celinio.net/techblog/?p=1207
Have a nice time.
im beginning with Ajax, i have problem with including Ajax files.
Ajax code written in original page (like index.php) and placed in (head) section works fine, but when i try to place code in external file (in js folder, where is placed prototype.js file), i don't get any response, not even in Firefox Error Console.
I haven't changed Ajax code except url for calling PHP function.
edit:
calling ajax files:
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/myValidation.js"></script>
</head><body>
....
Username: <input type="text" name="uname" id='uname' />
Available?
<span id="result"></span>
Email address: <input type="text" name="email" />
...
I embaded this function call in html. Validate function is from book "PHP and Script.aculo.us Web 2.0 app interfaces"
myValidation.js
function Validate(){
var user=$('uname');
var name="uname="+user.value;
var pars=name;
new Ajax.Request(
'myValidation.php',
{
method:'post', parameters:pars, asynchronous:true, onComplete: showAvailable
}
);
}
function showAvailable(originalRequest){
var newData=originalRequest.responseText;
$('result').innerHTML=newData;
}
This example is from mentioned book
You haven't shown us your myValidation.js file, but here are the typical reasons I see when people move from inline script blocks to external files and things stop working:
They put script blocks in the external JavaScript files. You probably didn't do that, but I've seen it often enough to mention it. Your external script is pure JavaScript, so for instance it should be:
function Validate() {
// ...
}
not:
<script type='text/javascript'>
function Validate() {
// ...
}
</script>
I've seen the latter a fair bit.
They put the JavaScript file in a location that doesn't match their script tag src.
They left an opening <!-- or closing --> in the script. Important not to do that, in external JavaScript files those are syntax errors.
They're using a web server that's case sensitive and the src attribute and the file's actual name don't match.
They're using a web server sensitive to permissions and the file doesn't have the right permissions.
In the case of the last two above, it's easy to check: Just open a new tab and actually enter the URL of the JavaScript file. If you see the JavaScript, great; if not, you probably have more information.
For issues like this (and hundreds of others), there's nothing like having a decent toolset. For debugging JavaScript on browsers, there are quite a few. There's Firebug (a Firefox add-in), Chrome's and Safari's Development Tools (built into the browsers), Microsoft Visual Studio or Script Debugger for debugging with IE, etc. Firebug and Dev Tools would both tell you about broken src links, as well as any exceptions, etc.
Have you checked that those files are accessible from the HTML code? And more - have you placed you scripts in the bottom of the page - because AJAX will bind it's handlers only to existing elements?
Problem solved.
In /js/ folder i had one php file, that i put there just because of simplicity. After moving it to other location all worked. Don't know if that is rule, nut no php files in /js/ folder. Thanks T.J and Tomasz
The main error shown in IE is : ' Could not complete the operation due to error 80020101.'
The error is displayed when the ExtJS framework tries to load a page containing a Ext grid component through an ajax request.
It works without problems in Firefox and Chrome.
Another error which is shown by IE is 'Expected identifier, string or number' which points to the line containing HTML inline style definition which is perfectly valid. I am not sure why this error is shown. I feel IE is pointing this error to the wrong place.
Could anyone please help me out on this?
"Could not complete the operation" errors in IE are usually caused by trying to modify the DOM before it is ready.
Move the JS so it fires in (for example) the onload event, or a JS library's ondomready event.
If you are loading a page using ajax and it has a inline script file like below add // before
the open comment tag
<script type="text/javascript">
// <!--
alert('text');
// -->
</script>
http://dracoblue.net/dev/could-not-complete-the-operation-due-to-error-80020101/137/