Cordova updating part of page - javascript

I created a login page with javascript. After a succesful the function loadMainActivity is called. As of now the contents are as follows:
async function loadMainActivity(){
document.getElementById("container").innerHTML = "This is a text.";
}
It works. However, now I want to load a complete HTML page upon a succesful login. I tried several plugins to this end. However, all of them require me to load a file. As I see it I have two options:
Provide an extra file with the app. This would enable my users to see the source, which I don't want.
Host the file on a server. This would require my users to have an active internet connection when using the app, which I also don't want, for now at least.
I thought about "stringifying" the HTML page and replacing "This is a text." with the obtained HTML string. That way I could keep the source closed. But this seems like a lot of extra steps. Besides, I cannot find a good method to do this stringification of HTML text.
How to solve this problem for a Cordova app?

I found that this can be done with the jQuery library, nothing specific to Cordova:
async function loadMainActivity(){
$.get("mainactivity.html", function( my_var ) {
document.getElementById("container").innerHTML = my_var;
});
}

Related

Javascript: Save content to Text File (No complicated Server stuff / HTTPRequest )

I am working on a small Project for myself. I wont upload a webpage but only run the files on localhost on my machine(HTML,CSS,JAVASCRIPT)
function saveData() {
$.post("testFile.txt", "New Content of the File ");
}
function getData() {
$.when($.get("testFile.txt")).done(function(requestedData) {
alert(requestedData);
});
}
Ok so this is basically a dummy Project to explain my Problem.
The methods are called by two different Buttons with an "onclick" event.
First Button which calls "getData()" works fine. The testFile.txt is located right next to the Html and Javascript file, and the getData() method correctly alerts the content of the text file as a String.
My Problem:
How do I make the saveData() method work? Do I misunderstand the $.post() method? (https://www.w3schools.com/jquery/jquery_ajax_get_post.asp)
I read so many forums and topics the last days but none of them solves the problem the way I´d need it, because I don´t wanna do all these difficult looking http-requests things - just reading and writing to this file that is located in the same folder then all my html and javascript Files
Thanks :)
$.post is for sending a POST http request.
Client-side javascript doesn't have permission to write to a client machine.
This would be a massive security hole if it did.
However
You've tagged node.js in your question, which can write to the local filesystem:
var fs = require('fs');
fs.writeFile("testFile.txt", "New Content of the File", function(err) {
//done
});

Multiple users using a spreadsheet at the same time, but it can only be used one at a time. What to do?

I'm using the Session.getEffectiveUser () command to return the results of the active user in the worksheet, but if another user enters the same sheet the results will conflict.
That is, only one can enter at a time. What can I do to keep this conflict from appearing?
Crazy solution that I thought: Is there any way that this worksheet doubles if I have 2 active users at the same time, and delete if that second user leaves?
Thx a lot!
And sorry for my bad english!
Here are the steps to deploy your code as a web app so that conflicts won't happen.
For this, you will need a front end where you will take inputs or whatever from the current user who will be accessing the web app.
Now, in your appscript screen only, you can go to File -> new -> html file, and name it as index.html or whatever you like. Code it in simple html format. Apply javascript also if you have to. For adding javascript externally, you can create another .html file and write your tag there. These all is simple html and javascript only.
Now, we have to link it with our appscript somehow. So for that, write this function in your appscipt:
function doGet(e)
{
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('YOUR_TITLE')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
And also write this line in your Index.html page(You can write it outside of <html> tags):
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
Now your code is ready to be deployed as web app. Go to Publish -> Deploy as web app...See that you have kept the option 'me' in Execute app as. Also, you can specify who can access your web app in the next option 'who has access to this app'.
Click update and run the latest code by clicking 'latest code' written in blue. You can also note it's URL so that you can include your web app in google sites etc.
Note that, every time you make new changes to the code, you should always choose project version 'new' and then click update.
Few tips:
To call functions of appscript from javascript, you can write like this:
google.script.run.withSuccessHandler(FUNCTION_NAME).APPSCRIPT_FUNCTION();
What it will do is, it will asynchronously call appscript function and when it is successfully executed, will execute the next javascript function named 'FUNCTION_NAME'.
How this will solve your problem?
Well, as you have deplyed the web app as 'me', whoever will run the web app will execute the code as if you yourself has executed the code, but at the same time, all featuers like Session.getActiveUser() will work individually. Hence, conflicts won't happen.
Try this yourself and you will have your doubts solved. If any queries please ask, community is always happy to help. :)

How to add html content generated by json call to page generated html code?

I have a page. Which contain json method to load data. I call this method on page load. It works properly. The problem is when I view source of that page I don't see the generated code.
My concern is the search engine will never see the content even if end user see it.
Is there anyway to add it? If so how it can be done?
Here is the example of code I use
$(function(){
//Call to the server to get data.
var content = "Some data"; //from the json call
$("#content").html(content);
});
});
Most if not all search engines will not recognize content inserted into a page from Ajax/Javascript, this is why you need to load this content with in the page if you want the search engine to recognize it.
Your question seems to me a copy of what's asked over here and in Is there anyway of making json data readable by a Google spider?
So, Progressive enhancement and Unobtrusive JavaScript are the way out..
In addition to these, optionally, but importantly, test the crawlability of your app: see what the crawler sees with "Fetch as Googlebot".

get a mutating url with javascript

i have the following question:
i'm currently working with a software(MicroStrategy, BI) wich has a functionality that exports reports to pdf, it works something like this:
each report has an unique ID, so you select the report to export, and with jsp i send this report's id to the exporting tool, and it generates a complete URL with some parameters that the MicroStrategy server will read to generate the PDF.
What i'm trying is to capture this pdf url and send it to a Java method that will save this pdf in the hard drive without prompting anything to the user.
My problem is that this URL doesn't generate instantly, it takes a while, AND, some redirections are made in the process.
So, after all that chitchat, how can i capture that damn URL?
What i'm doing is making the pdf load into an iframe, and then extracting the url with a js code i found searching, assigning it to a JSP variable, and then, once i have the pdf url, call the Java Method. But it is not working.
The JavaScript function is this:
<script language="text/javascript">
function getSrc()
{
var CurrentUrl = document.getElementById('miframe').contentWindow.location.href;
if(currentUrl.substr(length-5)==".pdf")
{
return currentUrl;
}
else
{
setTimeout(getSrc(),5000);
}
}
</script>
and this is the call i make to it:
<% jsp code
String currentUrl="<script>document.writeln(getSrc();)</script>";
more jsp code %>
The rest of the code is actually fine, tried it with a normal pdf URL and it saved the pdf into the disk.
Hope it is understadable, and thanks in advance!
Your main problem is that you are calling getSrc, not passing it to setTimeout (you are actually passing null to setTimeout, unless the second call to getSrc happens to work, in which case you are passing a string, which setTimeout can't process due to "syntax errors".
Instead, use setTimeout(getSrc,5000); - no parentheses after getSrc. This passes the function, rather than its result.
Also, currentUrl.substr(length-5) is wrong, partly because length is undefined (you need currentUrl.length in there), and partly because you need -4 to get the last four characters.
I don't know what kind of access you have to MicroStrategy, but there is a MicroStrategy java api that will allow you to execute the document and get pdf without capturing the url.
Check out their Knowledge Base for examples.
Why don't you just save the report/document with PDF format as default, in this way when you open the report it will automatically generated in PDF.
If you don't like the idea to save a report in PDF (for example because you need it also as regular report and you don't want to maintain two version of the same object), you can use URLAPI to generate the PDF using &executionMode=3 and &currentViewMedia=32.
Not sure about these parameters, the best way for you to figure out which they are (beside some MicroStrategy TN) is to export the report in PDF and check the url.

How to make a javascript like Disqus or IntenseDebate

I want to make an app that can display on any webpage, just like how Disqus or IntenseDebate render on articles & web pages.
It will display a mini-ecommerce store front.
I'm not sure how to get started.
Is there any sample code, framework, or design pattern for these "widgets"?
For example, I'd like to display products.
Should I first create a webservice or RSS that lists all of them?
Or can one of these Ajax Scripts simply digest an XHTML webpage and display that?
thanks for any tips, I really appreciate it.
Basically you have two options - to use iframes to wrap your content or to use DOM injection style.
IFRAMES
Iframes are the easy ones - the host site includes an iframe where the url includes all the nessessary params.
<p>Check out this cool webstore:</p>
<iframe src="http://yourdomain.com/store?site_id=123"></iframe>
But this comes with a cost - there's no easy way to resize the iframe considering the content. You're pretty much fixed with initial dimensions. You can come up with some kind of cross frame script that measures the size of the iframe contents and forwards it to the host site that resizes the iframe based on the numbers from the script. But this is really hacky.
DOM injection
Second approach is to "inject" your own HTML directly to the host page. Host site loads a <script> tag from your server and the script includes all the information to add HTML to the page. There's two approaches - first one is to generate all the HTML in your server and use document.write to inject it.
<p>Check out this cool webstore:</p>
<script src="http://yourdomain.com/store?site_id=123"></script>
And the script source would be something like
document.write('<h1>Amazing products</h1>');
document.write('<ul>');
document.write('<li>green car</li>');
document.write('<li>blue van</li>');
document.write('</ul>');
This replaces the original <script> tag with the HTML inside document.write calls and the injected HTML comes part of the original page - so no resizing etc problems like with iframes.
<p>Check out this cool webstore:</p>
<h1>Amazing products</h1>
<ul>
<li>green car</li>
<li>blue van</li>
</ul>
Another approach for the same thing would be separating to data from the HTML. Included script would consist of two parts - the drawing logic and the data in serialized form (ie. JSON). This gives a lot of flexibility for the script compared to the kind of stiffy document.write approach. Instead of outpurring HTML directly to the page, you generate the needed DOM nodes on the fly and attach it to a specific element.
<p>Check out this cool webstore:</p>
<div id="store"></div>
<script src="http://yourdomain.com/store_data?site_id=123"></script>
<script src="http://yourdomain.com/generate_store"></script>
The first script consists of the data and the second one the drawing logic.
var store_data = [
{title: "green car", id:1},
{title: "blue van", id:2}
];
The script would be something like this
var store_elm = document.getElementById("store");
for(var i=0; i< store_data.length; i++){
var link = document.createElement("a");
link.href = "http://yourdomain.com/?id=" + store_elmi[i].id;
link.innerHTML = store_elmi[i].title;
store_elm.appendChild(link);
}
Though a bit more complicated than document.write, this approach is the most flexible of them all.
Sending data
If you want to send some kind of data back to your server then you can use script injection (you can't use AJAX since the same origin policy but there's no restrictions on script injection). This consists of putting all the data to the script url (remember, IE has the limit of 4kB for the URL length) and server responding with needed data.
var message = "message to the server";
var header = document.getElementsByTagName('head')[0];
var script_tag = document.createElement("script");
var url = "http://yourserver.com/msg";
script_tag.src = url+"?msg="+encodeURIComponent(message)+"&callback=alert";
header.appendChild(script_tag);
Now your server gets the request with GET params msg=message to the server and callback=alert does something with it, and responds with
<?
$l = strlen($_GET["msg"]);
echo $_GET["callback"].'("request was $l chars");';
?>
Which would make up
alert("request was 21 chars");
If you change the alert for some kind of your own function then you can pass messages around between the webpage and the server.
I haven't done much with either Disqus or IntenseDebate, but I do know how I would approach making such a widget. The actual displaying portion of the widget would be generated with JavaScript. So, say you had a div tag with an id of commerce_store. Your JavaScript code would search the document, when it is first loaded (or when an ajax request alters the page), and find if a commerce_store div exists. Upon finding such a container, it will auto-generate all the necessary HTML. If you don't already know how to do this, you can google 'dynamically adding elements in javascript'. I recommend making a custom JavaScript library for your widget. It doesn't need to be anything too crazy. Something like this:
window.onload = init(){
widget.load();
}
var widget = function(){
this.load = function(){
//search for the commerce_store div
//get some data from the sql database
var dat = ajax('actions/getData.php',{type:'get',params:{page:123}});
//display HTML for data
for (var i in dat){
this.addDatNode(dat[i]);
}
}
this.addDatNode = function(stuff){
//make a node
var n = document.createElement('div');
//style the node, and add content
n.innerHTML = stuff;
document.getElementById('commerce_store').appendNode(n);
}
}
Of course, you'll need to set up some type of AJAX framework to get database info and things. But that shouldn't be too hard.
For Disqus and IntenseDebate, I believe the comment forms and everything are all just HTML (generated through JavaScript). The actual 'plugin' portion of the script would be a background framework of either ASP, PHP, SQL, etc. The simplest way to do this, would probably just be some PHP and SQL code. The SQL would be used to store all the comments or sales info into a database, and the PHP would be used to manipulate the data. Something like this:
function addSale(){ //MySQL code here };
function deleteSale(){ //MySQL code here };
function editSale(){ //MySQL code here };
//...
And your big PHP file would have all of the actions your widget would ever need to do (in regards to altering the database. But, even with this big PHP file, you'll still need someway of calling individual functions with your ajax framework. Look back at the actions/getData.php request of the example JavaScript framework. Actions, refers to a folder with a bunch of PHP files, one for each method. For example, addSale.php:
include("../db_connect.php");
db_connect();
//make sure the user is logged in
include("../authenticate.php");
authenticate();
//Get any data that AJAX sent to us
var dat = $_GET['sale_num'];
//Run the method
include("../PHP_methods.php");
addSale(dat);
The reason you would want separate files for the PHP_methods and run files, is because you could potentially have more than one PHP_methods files. You could have three method API's, one for displaying content, one for requesting content, and one for altering content. Once you start reusing your methods more and more, its best to have them all in one place. Rewritten once, rewritten everywhere.
So, really, that's all you'd need for the widget. Of course, you would want to have a install script that sets up the commerce database and all. But the actual widget would just be a folder with the aforementioned script files:
install.php: gets the database set up
JavaScript library: to load the HTML content and forms and conduct ajax requests
CSS file: for styling the HTML content and forms
db_connect: a generic php script used connect to the database
authenticate: a php script to check if a user is logged in; this could vary, depending on whether you have your own user system, or are using gravitars/facebook/twitter/etc.
PHP_methods: a big php file with all the database manipulation methods you'd need
actions folder: a bunch of individual php files that call the necessary PHP methods; call each of these php files with AJAX
In theory, all you'd have to do would be copy that folder over to any website, and run the install.php to get it set up. Any page you want the widget to run on, you would simply include the .js file, and it will do all the work.
Of course, that's just how I would set it up. I assume that changes in programming languages, or setup specifics will vary. But, the basic idea holds similar for most website plugins.
Oh, and one more thing. If you were intending to sell the widget, it would be extremely difficult to try and secure all of those scripts from redistribution. Your best bet would be to have the PHP files on your own server. The client would need to have their own db_connect.php, that connects to their own database and all. But, the actual ajax requests would need to refer to the files on your remote server. The request would need to send the url of the valid db_connect, with some type of password or something. Actually, come to think of it, I don't think its possible to do remote server file sharing. You'd have to research it a bit more, 'cuz I certainly don't know how you'd do it.
I like the Azmisov's solution, but it has some disadvantages.
Sites might not want your code on their servers. It'd be much better if you would switch from AJAX to loading scripts (eg. jQuery's getJSON)
So I suggest:
Include jquery hosted on google and a short jquery code from your domain to the client sites. Nothing more.
Write the script with cross-domain calls to your server (through getJSON or getScript) so that everything is fetched directly and nothing has to be inctalled on the client's server. See here for examples, I wouldn't write anything better here. Adding content to the page is easy enough with jQuery to allow me not mentioning it here :) Just one command.
Distribute easily by providing two lines of <script src= ... ></script>

Categories

Resources