I have written this code in js, but I need to rewrite it in ejs because it can't be seen by the user after the page is loaded. This is my code:
<script type="text/javascript" src="js/showads.js" class="deleteMe"></script>
<script type="text/javascript" class="deleteMe">
if(window.canRunAds == undefined){
window.location = "/welcome";
}
$('.deleteMe').remove();
</script>
I have this file named showads.js that contains a canRunAds variable. If the client has adblock enabled this file won't be imported, making the canRunAds variable undefined, and if is the client will be redirected to '/welcome', and then I just delete those 2 scripts, but it doesn't work, because the client can see it and maybe bypass it. Is there a way to write this in ejs, because when I tried it, I got an error saying window is undefined. Thank you!
It's true that you can run ejs in the client side without any server ( node.js ) but you can't access the DOM with it ( like you're doing now with JQuery ), so i assume all what you can parse to EJS
is :
<%
if(window.canRunAds == undefined){
window.location = "/welcome";
}
%>
JavaScript on the server doesn't have a window object. What can be done however is check that the window object is available at runtime, and conditionally run your code if it's accessible:
<script type="text/javascript" src="js/showads.js" class="deleteMe"></script>
<script type="text/javascript" class="deleteMe">
// Check if window exists, and that canRunAds doesn't
// On the server, the code within this block should never run
if(window && !window.canRunAds){
window.location = "/welcome";
}
// Bonus points using the same principle: Avoid assuming jQuery is available in
// inline script blocks.
if(window && window.jQuery) {
$('.deleteMe').remove();
}
</script>
Note that if your showads.js script is being run on the server, you'd also have to wrap any call to window in an if() check, otherwise the server will continue to throw an error.
Related
I am not a javascript guru, but try to use js-cookie.
I included the script: https://github.com/js-cookie/js-cookie: I downloaded it (LINK), and put it in my own js file on the server.
I then include it in a test file and read some cookie, but it keeps showing me the error "Cookies is not defined" in the browser console. What am I doing wrong :( ?
Code:
<html><head>
<script type="javascript" src="https://server/cookies.js"></script>
<script>
console.log("ALL COOKIES: " + Cookies.get());
</script></head>
<body></body>
I've not used the library, but a quick look at the source code shows that it exports Cookies with an uppercase C.
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
So try using the correct case.
console.log("ALL COOKIES: " + window.Cookies.get());
Also, everything on window is global. So you can simplify the code to this.
console.log("ALL COOKIES: " + Cookies.get());
Next time, in the JavaScript console on the browser. Just type window and enter to see what variables are global. You can also call it directly in the console to see what happens Cookies should print out a JavaScript object with descriptions of what functions it has.
If it's undefined then it wasn't loaded or is not global.
UPDATED:
The browser is not loading the JavaScript library because the mime-type is wrong. You have to use application/javascript as here:
<script type="application/javascript" src="https://server/cookies.js"></script>
You are using wrong versions of cookie.js on different routes/pages
Use the Latest
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
If it is not working, then try
<script src="https://cdn.jsdelivr.net/npm/js-cookie#rc/dist/js.cookie.min.js"></script>
Quick fix : Just use window. before calling it
window.Cookies.get()
Inspired by #ucMedia's answer, you can add the following line at the beginning of a script to fix any issues.
var Cookies = window.Cookies;
I was trying to run a simple client side javascript code in my Node JS server. But failed. My index.js file looks like below
response.writeHead(200, { 'Content-Type': 'text/html'});
response.write('Helloooo Wolrd!!');
response.end();
Now how do I put below ordinary javascript snippet in to above index.js page to run on Node JS(I want to know "Node way" of doing it AKA "Node Best Practise"),
<script type="text/javascript">
var ns = 1;
if (ns == 1){
alert('Oh..Node what have you done?');
}else{
alert('Node is not bad after all');
}
</script>
What I'm Really doing:
What I 'm really building is building a web page that runs on Node Js which will capture Gyro values like Device Orientation and Device Motion through a javascript of my iPhone and send it back to the web server. I can simply do this in Apache stack. But its too havey and slow. Thats why I want Node JS
I'm afraid it's still not very clear what you're looking for. Do you want an HTTP response that looks something like the following?:
Content-Type: text/html
Helloooo Wolrd!!
<script type="text/javascript">
var ns = 1;
if (ns == 1){
alert('Oh..Node what have you done?');
}else{
alert('Node is not bad after all');
}
</script>
If so, then you can either inline the script tag markup, as Peter Olson suggested, or look at streaming this into the response from a file.
If you want to do this:
Content-Type: text/html
Helloooo Wolrd!!
<script type="text/javascript" src="myScript.js"></script>
with the contents of your script in the file myScript.js, then you would probably be best served with a tool like Express.
If you are trying to get the equivalent of an alert to run on your server-side, then user2456263 has it right. There's simply no way to accomplish that. console.log is going to be your closest equivalent, and it's not particularly close.
If it's not one of these things you're trying to do, can you explain again?
From what I can understand you are looking for an alert function in node. There really isn't one. If you just want to print something to the console ( the ugly black box ) you can use console.log like this:
console.log(”Oh..Node what have you done?")
If you would like to not change a line of code you could wrap console.log in an alert function like this:
var alert = console.log;
And it will work as is. If you are looking for Dom interactions you can try jsdom.
EDIT :
If you want a javascript file which is capable of being run on both the client side and the server side you would do something like this.
if (typeof(process) !== 'undefined' && typeof(process.stdout) !== 'undefined') {
console.log('You are running Node.js');
} else {
alert("Why use console.log() when you can use alert?!");
}
This question is already answered in:
How to check whether a script is running under node.js?
we have the following situation:
in default.aspx we have a link:
test.
and the JS code:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
if(data.indexOf("http://")==0)
window.open(data);
else{
var win=window.open();
with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close();
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The callback can first be an url address or 2nd html code that must be executed.
Option 1 fits, but in option 2, a new window will be opened where the code has been written but not executed.
It's clear, since it happens in the stream, it can't be executed. So the question, how can you fix it? Maybe a refresh(), or similar?
Because of the requirement of the customer, the workflow can not be changed, so it must be solved within doPost().
EDIT
The response in case 2 is HTML like this. This part should be executed:
<HTML><HEAD>
<SCRIPT type=text/javascript src="http://code.jquery.com/jquery-latest.js">
</SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function() {
do_something...
});
</SCRIPT>
</HEAD>
<BODY>
<FORM>...</FORM>
</BODY>
</HTML>
Please help. Thanks.
In your JS code it should be something like this:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
//if(data.indexOf("http://")==0)
if (data.type!="url") //i will add a data type to my returned json so i can differentiate if its url or html to show on page.
window.open(); // I dont know why this is there. You should
else{
var win=window.open(data.url); //This data.url should spit out the whole page you want in new window. If its external it would be fine. if its internal maybe you can have an Action on one of your controllers that spit it with head body js css etc.
/* with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close(); */ // No need to write data to new window when its all html to be rendered by browser. Why is this a requirement.
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The overall logic is this
You do your ajax call on doPost
Find out if data returned is of type url or anything that need to open in new window
If it is url type it would have a url (check if this is not null or empty or even a valid url) then open a new window with that url. Have a read of W3C window.open for parameters
If you want to open and close it for some reason just do that by keeping the window handle but you can do this on dom ready event of that new window otherwise you might end up closing it before its dom is completely loaded. (someone else might have better way)
If its not url type then you do your usual stuff on this page.
If this does not make sense lets discuss.
Here's an interesting JS q... suppose you have:
host1.html on host1.com which references an external javascript (host2.js) on host2.com. In the host2.js, I'd like to get the location.hostname of the host serving the host2.js, but because host2.js is called inside of host1.html, it returns the location.hostname of host1.
Is there a way to get the location object of the external script within the external script being called?
I think similar questions have been asked before, and the answer was always no, this can't be done.
Workarounds:
Work through the parent document's script elements and, using a counter variable, find out which one we're in (ugh)
Output the current URL into the included script on server side, e.g. in PHP: script_current_url = <?php echo "http://".$_SERVER["HTTP_HOST"]."/".$_SERVER["REQUEST_URI"] (there's a variable for the protocol part too, I just forgot the name)
Set a variable before each <script> tag:
<script type="text/javascript">
script_current_url = "http://www.example.com/include.js";
</script>
<script type="text/javascript" src="http://www.example.com/include.js">
</script>
this is kludgy, but could be simplified by building a JS function that includes the file and sets the right variable automatically.
I like the server-side approach the best, but depending on your platform, it has other implications like having to send all .js resources through a resource-expensive interpreter.
Lets say I have a page with this code on it on www.foo.com:
<script src="http://www.bar.com/script.js" />
Can I write code from within script.js that can check that it was served from bar.com? Obviously document.location.href would give me foo.com.
Thanks!
var scripts = document.getElementsByTagName("script");
give you a collection of all the scripts in the page
After this you can read their src property to find your target (I hope you know how the script is called)
for (var i=0, limit=scripts.lenght; i< limit; i++) {
if (scripts[i].src.substr(<calculate your offset>) == scriptName) {
// Have you found your script, extract your data
}
}
The only way to find out the location of a non-worker script is the non-standard error.fileName, which is only supported by Firefox and Opera:
var loc = (new Error).fileName;
If the script is a worker thread (which of course it isn't), then you could just use the location object.
If it's really important, you could work around it by defining a string containing the script URL in front of each script tag:
<script type="text/javascript">SCRIPT_URL = "http://www.bar.com/script.js"</script>
<script src="http://www.bar.com/script.js" />
Inside the script file you can then access the URL
alert("my URL is "+SCRIPT_URL);
Not too elegant but should work.
You could also, if you have a server-side language like PHP and don't mind sending JS files through the interpreter (Big performance caveat!), do something like this within the JS file:
<script type="text/javascript">var my_url = "<? echo $_SERVER["REQUEST_URI"]; ?>"</script>
but that should really, really be the last resort.
You can wrap your script in a condition, kind of like an adult diaper, if you insist.
if(top.location.host==='www.bar.com'){
//the whole script goes here
}
else alert('Nyah Nyah Nyah!')