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

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

Related

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

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;

does window.location.reload(true) clear cache of asynchronous loaded resources? [duplicate]

How do I clear a browsers cache with JavaScript?
We deployed the latest JavaScript code but we are unable to get the latest JavaScript code.
Editorial Note: This question is semi-duplicated in the following places, and the answer in the first of the following questions is probably the best. This accepted answer is no longer the ideal solution.
How to force browser to reload cached CSS/JS files?
How can I force clients to refresh JavaScript files?
Dynamically reload local Javascript source / json data
Update: See location.reload() has no parameter for background on this nonstandard parameter and how Firefox is likely the only modern browser with support.
You can call window.location.reload(true) to reload the current page. It will ignore any cached items and retrieve new copies of the page, css, images, JavaScript, etc from the server. This doesn't clear the whole cache, but has the effect of clearing the cache for the page you are on.
However, your best strategy is to version the path or filename as mentioned in various other answers. In addition, see Revving Filenames: don’t use querystring for reasons not to use ?v=n as your versioning scheme.
You can't clear the cache with javascript.
A common way is to append the revision number or last updated timestamp to the file, like this:
myscript.123.js
or
myscript.js?updated=1234567890
Try changing the JavaScript file's src? From this:
<script language="JavaScript" src="js/myscript.js"></script>
To this:
<script language="JavaScript" src="js/myscript.js?n=1"></script>
This method should force your browser to load a new copy of the JS file.
Other than caching every hour, or every week, you may cache according to file data.
Example (in PHP):
<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>
or even use file modification time:
<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>
You can also force the code to be reloaded every hour, like this, in PHP :
<?php
echo '<script language="JavaScript" src="js/myscript.js?token='.date('YmdH').'">';
?>
or
<script type="text/javascript" src="js/myscript.js?v=<?php echo date('YmdHis'); ?>"></script>
window.location.reload(true) seems to have been deprecated by the HTML5 standard. One way to do this without using query strings is to use the Clear-Site-Data header, which seems to being standardized.
put this at the end of your template :
var scripts = document.getElementsByTagName('script');
var torefreshs = ['myscript.js', 'myscript2.js'] ; // list of js to be refresh
var key = 1; // change this key every time you want force a refresh
for(var i=0;i<scripts.length;i++){
for(var j=0;j<torefreshs.length;j++){
if(scripts[i].src && (scripts[i].src.indexOf(torefreshs[j]) > -1)){
new_src = scripts[i].src.replace(torefreshs[j],torefreshs[j] + 'k=' + key );
scripts[i].src = new_src; // change src in order to refresh js
}
}
}
try using this
<script language="JavaScript" src="js/myscript.js"></script>
To this:
<script language="JavaScript" src="js/myscript.js?n=1"></script>
Here's a snippet of what I'm using for my latest project.
From the controller:
if ( IS_DEV ) {
$this->view->cacheBust = microtime(true);
} else {
$this->view->cacheBust = file_exists($versionFile)
// The version file exists, encode it
? urlencode( file_get_contents($versionFile) )
// Use today's year and week number to still have caching and busting
: date("YW");
}
From the view:
<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">
Our publishing process generates a file with the revision number of the current build. This works by URL encoding that file and using that as a cache buster. As a fail-over, if that file doesn't exist, the year and week number are used so that caching still works, and it will be refreshed at least once a week.
Also, this provides cache busting for every page load while in the development environment so that developers don't have to worry with clearing the cache for any resources (javascript, css, ajax calls, etc).
or you can just read js file by server with file_get_contets and then put in echo in the header the js contents
Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:
<?php
touch('/www/control/file1.js');
touch('/www/control/file2.js');
touch('/www/control/file2.js');
?>
...the rest of your program...
It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping.
I had some troubles with the code suggested by yboussard. The inner j loop didn't work. Here is the modified code that I use with success.
function reloadScripts(toRefreshList/* list of js to be refresh */, key /* change this key every time you want force a refresh */) {
var scripts = document.getElementsByTagName('script');
for(var i = 0; i < scripts.length; i++) {
var aScript = scripts[i];
for(var j = 0; j < toRefreshList.length; j++) {
var toRefresh = toRefreshList[j];
if(aScript.src && (aScript.src.indexOf(toRefresh) > -1)) {
new_src = aScript.src.replace(toRefresh, toRefresh + '?k=' + key);
// console.log('Force refresh on cached script files. From: ' + aScript.src + ' to ' + new_src)
aScript.src = new_src;
}
}
}
}
If you are using php can do:
<script src="js/myscript.js?rev=<?php echo time();?>"
type="text/javascript"></script>
Please do not give incorrect information.
Cache api is a diferent type of cache from http cache
HTTP cache is fired when the server sends the correct headers, you can't access with javasvipt.
Cache api in the other hand is fired when you want, it is usefull when working with service worker so you can intersect request and answer it from this type of cache
see:ilustration 1 ilustration 2 course
You could use these techiques to have always a fresh content on your users:
Use location.reload(true) this does not work for me, so I wouldn't recomend it.
Use Cache api in order to save into the cache and intersect the
request with service worker, be carefull with this one because
if the server has sent the cache headers for the files you want
to refresh, the browser will answer from the HTTP cache first, and if it does not find it, then it will go to the network, so you could end up with and old file
Change the url from you stactics files, my recomendation is you should name it with the change of your files content, I use md5 and then convert it to string and url friendly, and the md5 will change with the content of the file, there you can freely send HTTP cache headers long enough
I would recomend the third one see
You can also disable browser caching with meta HTML tags just put html tags in the head section to avoid the web page to be cached while you are coding/testing and when you are done you can remove the meta tags.
(in the head section)
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0"/>
Refresh your page after pasting this in the head and should refresh the new javascript code too.
This link will give you other options if you need them
http://cristian.sulea.net/blog/disable-browser-caching-with-meta-html-tags/
or you can just create a button like so
<button type="button" onclick="location.reload(true)">Refresh</button>
it refreshes and avoid caching but it will be there on your page till you finish testing, then you can take it off. Fist option is best I thing.
I tend to version my framework then apply the version number to script and style paths
<cfset fw.version = '001' />
<script src="/scripts/#fw.version#/foo.js"/>
Cache.delete() can be used for new chrome, firefox and opera.
I found a solution to this problem recently. In my case, I was trying to update an html element using javascript; I had been using XHR to update text based on data retrieved from a GET request. Although the XHR request happened frequently, the cached HTML data remained frustratingly the same.
Recently, I discovered a cache busting method in the fetch api. The fetch api replaces XHR, and it is super simple to use. Here's an example:
async function updateHTMLElement(t) {
let res = await fetch(url, {cache: "no-store"});
if(res.ok){
let myTxt = await res.text();
document.getElementById('myElement').innerHTML = myTxt;
}
}
Notice that {cache: "no-store"} argument? This causes the browser to bust the cache for that element, so that new data gets loaded properly. My goodness, this was a godsend for me. I hope this is helpful for you, too.
Tangentially, to bust the cache for an image that gets updated on the server side, but keeps the same src attribute, the simplest and oldest method is to simply use Date.now(), and append that number as a url variable to the src attribute for that image. This works reliably for images, but not for HTML elements. But between these two techniques, you can update any info you need to now :-)
Most of the right answers are already mentioned in this topic. However I want to add link to the one article which is the best one I was able to read.
https://www.fastly.com/blog/clearing-cache-browser
As far as I can see the most suitable solution is:
POST in an iframe. Next is a small subtract from the suggested post:
=============
const ifr = document.createElement('iframe');
ifr.name = ifr.id = 'ifr_'+Date.now();
document.body.appendChild(ifr);
const form = document.createElement('form');
form.method = "POST";
form.target = ifr.name;
form.action = ‘/thing/stuck/in/cache’;
document.body.appendChild(form);
form.submit();
There’s a few obvious side effects: this will create a browser history entry, and is subject to the same issues of non-caching of the response. But it escapes the preflight requirements that exist for fetch, and since it’s a navigation, browsers that split caches will be clearing the right one.
This one almost nails it. Firefox will hold on to the stuck object for cross-origin resources but only for subsequent fetches. Every browser will invalidate the navigation cache for the object, both for same and cross origin resources.
==============================
We tried many things but that one works pretty well. The only issue is there you need to be able to bring this script somehow to end user page so you are able to reset cache. We were lucky in our particular case.
window.parent.caches.delete("call")
close and open the browser after executing the code in console.
Cause browser cache same link, you should add a random number end of the url.
new Date().getTime() generate a different number.
Just add new Date().getTime() end of link as like
call
'https://stackoverflow.com/questions.php?' + new Date().getTime()
Output: https://stackoverflow.com/questions.php?1571737901173
I've solved this issue by using
ETag
Etags are similar to fingerprints, and if the resource at a given URL changes, a new Etag value must be generated. A comparison of them can determine whether two representations of a resource are the same.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete
Cache.delete()
Method
Syntax:
cache.delete(request, {options}).then(function(found) {
// your cache entry has been deleted if found
});

Google jspai fails to load, but only for customer

My website needs to use the Google Earth plugin for just a bit longer (I know, the API is deprecated, but I'm stuck with it for several more months). I load it by including google.com/jsapi, then calling google.load like so:
...
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("earth", "1", {"other_params": "sensor=false"});
google.setOnLoadCallback(function () {
// call some JavaScript to begin initializing the GE plugin
});
</script>
</body>
</html>
This works well from multiple computers and with multiple browser inside our company's firewall. It works well from my home computer, and from my colleagues' home computers. However, when my customer tries to load it, she gets an error message that google is not defined on the line that begins google.load(.
Of course, global variable google is defined at the start of file www.google.com/jsapi, so presumably that file isn't loading. I initially assumed that her corporate firewall was blocking that file, but when I asked her to paste "https://www.google.com/jsapi" into her browser's address bar, she said that immediately loaded up a page of JavaScript.
The entire output to the browser console is:
Invalid URI. Load of media resource failed. main.html
ReferenceError: google is not defined main.html:484
And I believe the Invalid URI business is just because we don't have a favicon.ico file.
She is running Firefox 35.0.1, though she says the same error occurred with IE (she didn't mention the version of IE).
Short of asking her to install Firebug, which I don't think is going to be feasible, how can I troubleshoot this issue?
I'm really not sure with that assumption but:
Could it be, that your first script loads asynchronous? Then for slow connections (your customer) this problem would occur (i know that you are not using the async tag - but maybe the source can trigger to load async).
Best thing to do here is to make sure that the Google code you're using is the sync kind and redeploy.
Also https://bugsnag.com/ can be a really interesting tool for you. Just implement the js and you can track every error your customer gets.
Redeploy your code as follows,
<script type="text/javascript">
try {
google.load("earth", "1", {"other_params": "sensor=false"});
google.setOnLoadCallback(function () {
// call some JavaScript to begin initializing the GE plugin
});
} catch (e) {
$.post('http://<your-remote-debug-script-or-service>',e)
}
</script>
Then, when your customer encounters the error, the full details will be sent directly to your server and you can troubleshoot as necessary.
It could be something as simple as the clients browser is blocking javascript from being executed. Maybe specifically blocking your domain or something crazy like that.
Can you try an external script that loads the google jsapi, then put your code in the callback to ensure it is loaded?
<script type="text/javascript">
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://www.google.com/jsapi", function(){
google.load("earth", "1", {"other_params": "sensor=false"});
google.setOnLoadCallback(function () {
// call some JavaScript to begin initializing the GE plugin
});
});
</script>
(Modified from http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/)
You may also want to look at jsapi Auto-Loading to minimize what is loaded, but it may get tricky with an older library. https://developers.google.com/loader/

How do I rotate an ad on a page loading the list of ads from an external file using JavaScript?

I'm trying to load a variable from a file using javascript. I've found some examples but I can't seem to make it work and could really use some help on getting my syntax right.
Basically, I want to load a random ad image on a page, but I would like the list of ads to be pulled from a file. Currently I'm loading the images using the following script which I found on the internet:
<script type="text/javascript">
var picPaths = [
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
]
var oPics = [];
for(i=0; i < picPaths.length; i++){
oPics[i] = new Image();
oPics[i].src = picPaths[i];
}
curPic = Math.floor(Math.random()*oPics.length);
window.onload=function(){
document.getElementById('imgRotator').src = oPics[curPic].src;
}
</script>
I have been trying to get the picPath variable value to load from a file (instead of stating it in the code). I found some code here on stackoverflow and tried adjusted it to the following:
var picPaths = new XMLHttpRequest();
picPaths.open('GET', '/images/liveimages.inc');
picPaths.send();
I also created the file /images/liveimages.inc which containts the following:
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
But, alas, it’s not working and I’m not programmer enough to fix it. :-( I'm thinking my syntax is off but my code could be off too since I am not a JavaScript guy.
Any help would be appreciated and thanks for taking the time to read (and respond) to my question! :-D
If you store the data file as JSON you can use AJAX/XMLHTTPRequest to fetch it, and JSON.parse (available in all modern browsers) to read it.
An easier way perhaps is just to have a script that contains just the data, like:
var picPaths = [
'/images/ad-1.jpg',
'/images/ad-2.jpg',
'/images/ad-3.jpg',
'/images/ad-4.jpg'
];
And then include your scripts in the correct order:
<script type="text/javascript" src="picpaths.js"></script>
<script type="text/javascript" src="ad_script.js"></script>
ad_script.js will be able to access picPaths.
You could have some server-side script generate picpaths.js for you, for instance by looking at the contents of a folder or a database and pulling the ad info from that.

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