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())
//...
Related
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') )
I have the task of writing JavaScript code to extract the text from an
external web page and count the number of occurrences of each word in the text. I am also given these two assumptions:
You may assume that the web page will be on the same file system as the web page
written for the exercise.
You may also assume that the web page comprises correctly-formed XHTML
I've worked out from some similar posts on this site how to get the text from the html using the .textContent and .innerText.
I want the user to be able to specify the webpage in a text input.
What I don't understand is getting the other html document in some sort of way so that I can get the text and parse it.
use jQuery.load()
var targetDiv = document.getElementById('my-div');
var input = $("input");
$(targetDiv).load(input.value);
Executing javascript in someones browser means you are telling the user to do something for you. To prevent you using that someone to load a completely foreign page for yourself is something limited by security reasons to protect the user and the external site. If that foreign site is allowed you to download / parse their content then jquery.get is enough for this.
working on webmarketing, my IT is telling me that Iframe tags are more and more touchy regarding security matters. I am not allowed to use javascript tags either however image tags are too simple to let me piggyback third party tags.(because they do not allow scripts to be executed)
Any ideas of what type of tags or type of code I could use or modify to fulfill both technical and commercial conditions, please?
(a mix of javascript and flash website)
thank you
you could use some server side scripting language (eg PHP) as your image file source. That way, you execute whatever you need server side, while serving the "simple image". And example :
<img src="/images/image.php?img=asdf" />
on the server side, you can have a PHP session, along with any data that's relevant to the request. Depending on what type of data you want to harvest, it might be difficult/impossible without any Javascript.
This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.
I am aware of the hidden iFrame trick as mentioned here (http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) and in other answers.
I am interested in a similar problem:
How can I use Javascript to download the current page (IE: the current DOM, or some sub-set of it) as a file?
I have a web page which fetches results from a non-deterministic query (eg. a random sample) to display to the user. I can already, via a querystring parameter, make the page return a file instead of rendering the page. I can add a "Get file version" button (our standard approach) but the results will be different to those displayed because it is a different run of the query.
Is there any way via Javascript to download the current page as a file, or is copying to the clipboard my only option?
EDIT
An option suggested by Stefan Kendall and dj_segfault is to write the result server side for later retrieval. Good idea, but unfortunately writing files server side is out of the question in this instance.
How about shudder passing the innerHTML as a post parameter to another page?
You can try with the protocol data:text/attachment
Like in:
<html>
<head>
<style>
</style>
</head>
<body>
<div id="hello">
<span>world</span>
</div>
<script>
(function(){
document.location =
'data:text/attachment;,' + //here is the trick
document.getElementById('hello').innerHTML;
//document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>
Edit after shesek comment
To add to Mic's terrific answer above, some additional points:
If you have Unicode content (Or want to preserve indentation in the source), you need to convert the string to Base64 and tell the Data URI to treat the data as such:
(function(){
document.location =
'data:text/attachment;base64,' + // Notice the new "base64" bit!
utf8_to_b64(document.getElementById('hello').innerHTML);
//utf8_to_b64(document.documentElement.innerHTML); //To Download Entire Html Source
})();
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
utf_to_b64() via MDN -- works in Chrome/FF.
You can drop this all into an anchor tag, allowing you to set the download attribute:
<a onclick="$(this).attr('href', 'data:text/plain;base64,' + utf8_to_b64($('html').clone().find('#generate').remove().end()[0].outerHTML));" download="index.html" id="generate">Generate static</a>
This will download the current page's HTML as index.html and removes the link used to generate the output. This assumes the utf8_to_b64() function from above is defined somewhere else.
Some useful links on Data URIs:
MDN article
MSDN article
Depending on the size and if support is needed for ancient browsers, but you can consider creating a dynamic file using data: URIs and link to it. I'be seen several places that do that. To get the brorwser to download rather than display it, play around with the content type you put in the URI and use the new html5 download attribute. (Sorry for any typos, I'm writing from my phone)
I don't think you're going to be able to do it exactly the way you want to. JavaScript can't create a file and download it for security reasons. Nor can it create it on the server for download.
What I would do if I were you is, on the server side, create an output file with the session ID in the name in a temp directory as you create the output for the web page, and have a button on the web page with a link to that file.
You'll probably want a separate process to remove files over a day old or something like that.
Can you not cache the query results, and store it by some key? That way you can reference the same report output forever, or until your file garbage collector comes along. This also implies that you can create static URLs to report outputs, which tends to be nice.