Implement one javascript code and load dynamically more scripts - javascript

i would like to give our client one javascript code (e.g. Google Tag Manager) he/she has to implement on the website.
When this script is called i want to have a config file per client which features this client has enabled. Lets say we have 3 features:
feature1.js
feature2.js
feature3.js
Every feature is doing something else on the website (e.g. tracking user data, displaying a widget, etc.)
My questions:
1. How would you store the config which features are enabled? This should be flexible, whenever we add feature4.js, we just can enable it and the script will be loaded and the client does not have to implement new js code
2. Regarding performance, how would you do it? We are using AWS CloudFront.
Basically this is kind of the Google Tag Manager concept: One Code and on backend side the client can decide which JS code to be loaded / injected.
Thank you very much for your ideas!

A simple way is just to inject the required lib into the DOM.
On this example, the script will be the second element on the page.
You may want sometimes to inject at the bottom of the DOM.
function userlib1(){
let lib = document.getElementsByTagName('*')[1],
inj = document.createElement('script')
inj.src = 'https://..../script.js'
lib.appendChild(inj)
}
To store user data's, we can use localstorage, just like this:
localStorage.setItem('userdata','lib4')
console.log( localStorage.getItem('userdata') )

Related

How can I handle dynamic content in external javascript file?

I have a website in several languages and it happens that there are some visitors who for some reason are viewing a page in a different language than that of their browser settings.
Therefore, if their browser language is one of those the site is translated into, I suggest they switch to their preferred language.
I do this with a div containing a message at the top of the page.
According to your settings, we suggest you to view the content of this page in the following language: {language link}.
{Denied option with link}
The message is shown in the current language (I have all the translations of course), while {language link} is taken from the user's settings. The javascript code is generated Serverside with PHP and managed by Javascript in the HTML
<script>
// instructions loaded, matching user conditions...
</script>
Is there any way to manage it in an external js file? How to do? Obviously, I'm not interested in preparing n*n combinations of files and uploading the one that matches the visitor's situation.
How to do?
Thank you!
You can probably write particular JavaScript server side that assigns data to a global variable, in addition to your external script.
In the server-rendered page, it'd look something like:
<script>
var userSettingsLanguageLink = '{language link}';
</script>
And then in your external script, something like:
if (userSettingsLanguageLink !== getBrowserLanguage())
//...

Creating embedded web browser or iframe in Excel Javascript API

I'm trying to create an Office-JS project which will take some form data, which i've created inside a Excel Taskpane Form. Then when they submit it will send a request to my website which will process the form and spit back some HTML/JS as strings for Bokeh or ggplot.
Thus my question: Is there a way to create an "embedded" iframe or Microsoft web browser that I can put html/js into and send the "left side" with context.sync() using the Excel JS API?
I've found documentation about using the built in graphs, but I was hoping to pass back more complex graphs: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-charts
Something like this:
To put it into code, this is where i'm stuck:
function getData(){
return Excel.run( function (context) {
return context.sync().then( function () {
.ajax({
<my url and form data>
}).done( function(data, status, xhr) {
var browser = create_browser(); // I do not know what this would be
// Bokeh route returns data["script"] & data["div"]
// (\n<script type="text/javascript">\n ... <div class="bk-plotdiv" id="30d5b5cf-da07-4382-9b93-09ac605ba96d"></div>\n</div>)
browser.render(data["script"], data["div"])
sheet.getRange().values = browser
})
})
})
I think what you might want is a Content add-in. This is an example of one: Excel Content Add-in Humongous-Insurance. Some more information at Create new objects in Office documents. But you can't have both a browser in a task pane and one in the Excel document. These are different add-in types and the add-in manifest specifies the type. You will need to have the form as well as the resulting graphic in the content window.
David E. Craig describes a way of communicating between a Task Pane Office app and a Content Office app (what would be embedded on the spreadsheet) on his website. He summarizes it as follows:
The solution is to use the Document as a communication medium. In the particular case we used CustomXMLParts in the document. Here is how it would work:
One add-in would need to send an update to the other, so it would write a CustomXMLPart with a specific namespace and a “context” (basically, I am the TaskPane communicating) to the document.
Both add-ins will have a window.setInterval() thread running to check the documents for CustomXMLParts in that given namespace.
The timer on the Content Add-in would fire, find the new customXMLPart from the taskpane, read the contents and then update itself as needed and finally, delete the CustomXMLPart.

Is it possible to retrieve text files from HTML app directory without HTTP request or <input>?

I'm working on an HTML/javascript app intended to be run locally.
When dealing with img tags, it is possible to set the src attribute to a file name with a relative path and thereby quickly and easily load an image from the app's directory. I would like to use a similar method to retrieve a text file from the app's directory.
I have used TideSDK, but it is less lightweight. And I am aware of HTTP requests, but if I remember correctly only Firefox has taken kindly to my use of this for local file access (although accessing local images with src does not appear to be an issue). I am also aware of the FileReader object; however, my interface requires that I load a file based on the file name and not based on a file-browser selection as with <input type="file">.
Is there some way of accomplishing this type of file access, or am I stuck with the methods mentioned above?
The browser will not permit you to access files like that but you can make javascript files instead of text files like this:
text1.js:
document.write('This is the text I want to show in here.'); //this is the content of the javascript file
Now call it anywhere you like:
<script type="text/javascript" src="text1.js"></script>
There are too many security issues (restrictions) within browsers making many local web-apps impossible to implement so my solution to a similar problem was to move out of browsers and into node-webkit which combines Chromium + Node.js + your scripts, into an executable with full disk I/O.
http://nwjs.io/
[edit] I'm sorry I thought you wanted to do this with TideSDK, I'll let my answer in case you want to give another try to TideSDK [/edit]
I'm not sure if it's what you're looking for but I will try to explain my case.
I've an application which allow the user to save the state of his progress. To do this, I allow him to select a folder, enter a filename and write this file. When the user open the app, he can open the saved file, and get back his progress. So I assume this enhancement is similar of what you are looking for.
In my case, I use the native File Select to allow the user to select a specific save (I'm using CoffeeScript) :
Ti.UI.currentWindow.openFileChooserDialog(_fileSelected, {
title: 'Select a file'
path: Ti.Filesystem.getDocumentsDirectory().nativePath()
multiple: false
})
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.UI.UserWindow-method-openFileChooserDialog)
When this step is done I will open the selected file :
if !filePath?
fileToLoad = Ti.Filesystem.getFile(scope.fileSelected.nativePath())
else
fileToLoad = Ti.Filesystem.getFile(filePath)
data = Ti.JSON.parse(fileToLoad.read())
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Filesystem)
Please note that those snippets are copy/paste from my project and they will not work without the rest of my code but I think it's enough to illustrate you how I manage to open a file, and read his content.
In this case I'm using Ti.JSON.parse because there is only javascript object in these files but in your case you can just get the content. The openFileChooserDialog isn't mandatory, if you already know the file name, or if you get it from another way you can use Ti.Filesystem in your own way.

How can I *locally* save an .html file generated by javascript (running on a *local* .html page)?

So I've been researching this for a couple days and haven't come up with anything conclusive. I'm trying to create a (very) rudimentary liveblogging setup because I don't want to pay for something like CoverItLive. My process is: Local HTML file > Cloud storage (Dropbox/Drive/etc) > iframe on content page. All that works, and with some CSS even looks pretty nice despite the less-than-awesome approach. But here's the thing: the liveblog itself is made up of an HTML table, and I have to manually copy/paste the code for a new row, fill in the timestamp, write the new message, and save the document (which then syncs with the cloud and shows up in the iframe). To simplify the process I've made another HTML file which I intend to run locally and use to add entries to the table automatically. At the moment it's just a bunch of input boxes and some javascript to automate the timestamp and write the table row from the input data.
Code, as it stands now: http://jsfiddle.net/LukeLC/999bH/
What I'm looking to do from here is find a way to somehow export the generated table data to another .html file on my hard drive. So far I've managed to get this code...
if(document.documentElement && document.documentElement.innerHTML){
var a=document.getElementById("tblive").innerHTML;
a=a.replace(/</g,'<');
var w=window.open();
w.document.open();
w.document.write('<pre><tblive>\n'+a+'\n</tblive></pre>');
w.document.close();
}
}
...to open just the generated table code in a new window, and sure, I can save the source from there, but the whole point is to eliminate steps like that from the process.
How can I tell the page to save the generated code to a separate .html file when I click on the 'submit' button? Again, all of this happens locally, not on a server.
I'm not very good with javascript--and maybe a different language will be necessary--but any help is much appreciated.
I suppose you could do something like this:
var myHTMLDoc = "<html><head><title>mydoc</title></head><body>This is a test page</body></html>";
var uri = "data:application/octet-stream;base64,"+btoa(myHTMLDoc);
document.location = uri;
BTW, btoa might not be cross-browser, I think modern browsers all have it, but older versions of IE don't. AFAIK base64 isn't even needed. you might be able to get away with
var uri = "data:application/octet-stream,"+myHTMLDoc;
Drawbacks with this is that you can't set the filename when it gets saved
You cant do this with javascript but you can have a HTML5 link to open save dialogue:
<a href="pageToDownload.html" download>Download</a>
You could add some smarts to automate it on the processed page after the POST.
fiddle : http://jsfiddle.net/ghQ9M/
Simple answer, you can't.
JavaScript is restricted to perform such operations due to security reasons.
The best way to accomplish that, would be, to call a server page that would write
the new file on the server. Then from javascript perform a POST request to the
server page passing the data you want to write to the new file.
If you want the user to save the page to it's file system, this is a different
problem and the best approach to accomplish that, would be to, notify the user/ask him
to save the page, that page could be your new window like you are doing w.open().
Let me do some demonstration for you:
//assuming you know jquery or are willing to use it :)
var html = $("#tblive").html().replace(/</g, '<');
//generating your download button
$.post('generate_page.php', { content: html })
.done(function( data ) {
var filename = data;
//inject some html to allow user to navigate to the new page (example)
$('#tblive').parent().append(
'Check your Dynamic Page!');
// you data here, is the response from the server so you can return
// your new dynamic page file name here.
// and maybe to some window.location="new page";
});
On the server side, something like this:
<?php
if($_REQUEST["content"]){
$pagename = uniqid("page_", true) . '.html';
file_put_contents($pagename, $_REQUEST["content"]);
echo $pagename;
}
?>
Some notes, I haven't tested the example, but it works in theory.
I assume that with this the effort to implement it should be minimal, assuming this solves your problem.
A server based solution:
You'll need to set up a server (or your PC) to serve your HTML page with headers that tell your browser to download the page instead of processing the HTML markup. If you want to do this on your local machine, you can use software such as WAMP (or MAMP for Mac or LAMP for Linux) that is basically a web server in a .exe. It's a lot of hassle but it'll work.

Retrieve text from external HTML/asp page with JavaScript

I am using an external asp page (On the company's server - not related to me beside the fact that I'm using it for my job).
The asp page has one query in it, I'm writing something in it and it gives me some information.
In the information there is a certain line with constant header (let's assume 'HEADER'), I want to build an HTA that pulls the line that contains 'HEADER' to my HTA and display only this line.
I think that this isn't possible without any server interaction, but I'm asking anyway.
Can someone think of a way doing it?
Thanks,
Rotem
You can use an Ajax request to pull data from that page. The javascript page needs to be on the same server as the page you want to pull data from because of cross site scripting prevention in most browsers. Here is a good place to start: http://www.w3schools.com/ajax/ajax_intro.asp
Ok, I made something with JavaScript, using Telnet.
It isn't working for all sites, when I'll be at work I'll check it, but I think this will do the job.
The code:
<script type="text/javascript">
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("telnet -fc:/telnetlog.txt www.google.com 80"); // This will save me the source file + minor junk!
setTimeout("WshShell.SendKeys('GET / HTTP/1.0~~')",1000); // Enter the command it telnet </script>
Thanks for the brainstorming,
Rotem

Categories