"Cookies not defined" in standalone js-cookie javascript lib? - javascript

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;

Related

How to rewrite js code in ejs

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.

Why is $(document).ready(); undefined?

I thought that I was doing everything right, however I keep getting this error. $(document).ready(); // undefined in the console. I imported my jquery script.
<script src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script >
$(document).ready(function(){
$("div#chat").hide();
});
function send_file(){
}
function remove_selected(){
}
function changeToFile(){
}
function chatToProfile(){
}
function changeToChat(){
}
</script>
If you're running this file locally (which I suspect you are...), this will attempt to find the referenced file on your local system, which will not be there.
To fix this, instead use this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Need to add http: in your script reference. try this:
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
i use like this :) and those who says HTTP required. read this article for relative Protocol URL Protocol relative url
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='/js/jquery-1.8.3.min.js' type='text/javascript'%3E%3C/script%3E")); //Load the Local file (if google is down for some reason)
}
</script>
Script url that you are using for loading is perfect.
You can check your Url by posting "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" in browser url if you will get the javascript text file then it is working.
I test it and that url is working fine on my side.Error is some where else either there is restriction(security resons) or there is internet connection problem on the system when ever you run that web application on the system.
solution is either use minified copy in you web application and provide the relative path or use
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='/js/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
You always can check if jQuery is already loaded in the memory and the library is ready to use:
if (typeof jQuery !== 'undefined') {
//do whatever here
}

JQuery .getJson wont load local file plus how to convert to JavaScript object.

Hey guys I am trying to learn how to use JSON files. I understand the basics but I am trying to grasp loading them into an HTML file and I am having a couple of difficulties.
The first difficulty I am having is that if I put in the full file extension to load the file I get an error 'expected hexadecimal digit'. I did some research on it and I think it is because in the file extension it is \u so it is expecting a hexadecimal but I am not sure how to work around it.
The second problem I am having is that if I just use the file extension users.json it works in my editor but not in a browser. It is not loading the file at all, the code is fine (I believe). I think it is just not loading the file because of the file extenion.
Suggestions on how to fix my problems? Thanks in advance.
<body>
for output
<div id="forOutput"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var output;
$(document).ready(function(){
alert("JQuery loaded");
});
$.getJSON('C:\Users\Spencer\Desktop\JSJqueryTesting\JSONTesting\users.json', function(data) {
output = data;
for (var i in data.users) {
alert(data.users[i].firstName + " " + data.users[i].lastName+ " " + data.users[i].joined.month);
}
});
$("#forOutput").html("User 1 lastname: " + output.users[1].lastName);
</script>
The file extension is perfect (.json), however, you can't load local files (because of security reasons). If what you are trying to do, were possible, that would mean any website could access all your local files. Now that's really not such a good idea, and therefore (by default) only files that share the same domain(e.g. stackoverflow.com/*) are allowed. This is called Same Origin Policy.

Include remoted Library (API 4.5 Mapy.cz) to Google Chrome Extension

I am confused. I'am trying to make little chrome extension (popup) and I need connect to remoted API.
This is, what I would use, if it is a standard web page:
<script type="text/javascript" src="http://api4.mapy.cz/loader.js"></script>
<script type="text/javascript">Loader.load();</script>
I experimented with including new element script to head (not works for me). But I couldn't believe, there is no easier way...
Please, show me the best way.
EDIT:
Linking the API loader is fine and works. Thanks to #serg. So, my code of popup looks like this:
<script type="text/javascript" src="http://api4.mapy.cz/loader.js"></script>
<script type="text/javascript">
Loader.load();
var center = SMap.Coords.fromWGS84(16.61574, 49.20315);
</script>
Object Loader is defined and it is OK. Loader should load the whole API either object SMap. But SMap is undefined. What next?
If you need to make ajax requests to this remote API, you need to list API domain in the permissions in your manifest:
{
"permissions": [
"http://api4.mapy.cz/"
],
}
Finally I ask developer from Mapy.cz and they gave the solution. Instead of using Loader.load() which cause including additional script and async load - use this way:
Loader.async = true;
Loader.load(null, null, function(){
alert(123); // it works...
// custom code calling objects etc. from API
// ...
});
Final Example of usage

qt.webChannelTransport undefined in QWebEngineView

I ran into a problem using QWebChannel for accessing an object from JavaScript. I'm currently using Qt5.4.2.
Here's my CPP code :
myObject::myObject(QWidget *parent)
: QMainWindow(parent)
{
QWebEngineView* m_pView = new QWebEngineView(this);
QWebChannel channel;
channel.registerObject(QString("myObject"), this);
m_pView->load(QUrl("file:///D:/index.html"));
setCentralWidget(m_pView);
}
In my index.html, I am including qwebchannel.js :
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
And in my javascript file, I am trying to retrieve my object like this :
new QWebChannel(qt.webChannelTransport, function(channel) {
var myObject = channel.objects.myObject;
});
However, I get the following error in the console :
Error: qt is not defined
I also tried to replace it with navigator.qtWebChannelTransport but I got :
Error: transport is not defined
Can somebody tell me what did I do wrong? Thanks.
Edit : Is qt.webChannelTransport only accessible with Qt5.5? It seems to be the case when I read the doc of QWebEnginePage::setWebChannel...
You must setWebChannel before load url
Thats correct.
QWebChannel integration with QWebEngine is only available from version 5.5 as stated here by Milian, the main developer of the module.
You have to google qwebchannel.js to get the default code (it's a lot of code actually) or get it from out of Qt's directories somehow. I put mine under <qrc>/qtwebchannel/qwebchannel.js. Then make sure you import it as a regular javascript into your index.html but with source as "qrc:/qtwebchannel/qwebchannel.js". I had your exact error earlier today, and something I did fixed it - was probably including that script.
For others having the same issue but using Qt 5.5+, make sure you have QT += webchannel in your .pro file.

Categories