Getting Page Load Progress with Ajax - javascript

Well, i am new to Ajax and JQuery, I struggled to compile this. I'm trying to load URL with ajax navigation and with popstate retrieving back and front navigations. The below code works well but my problem is integrating the Progress Indicator of the page i'm trying to load when the link is clicked using Pace Page Progress Bar Plugin.
<html>
<head>
<meta charset="utf-8" />
<div id="render-me">
<title>jQuery Ajax Test</title>
<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://www.gossipper.com/content/css/inspired-mob/styles/pace-theme-center-atom.css" />
<script>
paceOptions = {
ajax: true, // disabled
document: true, // disabled
eventLag: true, // disabled
elements: {
selectors: ['#render-me']
}
};
</script>
<script src="https://www.gossipper.com/content/css/inspired-mob/js/pace.js"></script>
<script type="text/javascript"><!--
$(document).ready(function(e){
$.ajaxSetup ({
cache: false
});
var page;
$('a.lnk').click(function(){
page = $(this).attr('href');
$('#render-me').load(page + ' #render-me');
if(page != location.href){
window.history.pushState({path:page},'',page);
$(window).bind("popstate", function() {
link = location.pathname.replace(/^.*[\\/]/, ""); // get filename only
$('#render-me').load(link + ' #render-me');
});
}
return false;
});
document.addEventListener('gg', function(){
document.querySelector('.pace').classList.remove('pace-inactive');
document.querySelector('.pace').classList.add('pace-active');
document.querySelector('.pace-progress').setAttribute('data-progress-text', percentComplete.value + '%');
document.querySelector('.pace-progress').setAttribute('style', '-webkit-transform: translate3d(' + percentComplete.value + '%, 0px, 0px)');
});
$(window).on({
popstate:function(e){
page = location.href;
$('#render-me').load(page + ' #render-me');
}
});
});
</script>
</head>
<body>
<h1>Web page test.html</h1>
Get extern
<div id="content">Initial content in test.html</div>
</body>
</div>
</html>
As i stated above, am a newbie to Ajax, JQuery and Javascript. I struggled to compile this, i need help getting this to work.

The problem in your code is your script source for pace, css source for pace and the proper placing of html elements.
I tried to go in the sources of your script and css for pace but it is not found.
You don't need to encapsulate all of your element in the <div id="render-me">.
Based from https://www.w3schools.com/html/html_head.asp
The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag.
HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, links, scripts, and other meta information.
The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>
So you must remove the div in the head, fix the sources and put the <div id="render-me"> inside body.
Here is your code that I fixed: https://jsfiddle.net/uqbysq1a/1/

Related

How can I change default backround color of botman.io widget

Im using botman.io package for chatboot widget.
Everything works perfectly but problem is that i can't change default background color of chat widget. On inspect console it shown that boman widget calls ( https://cdn.jsdelivr.net/npm/botman-web-widget#0.0.20/build/assets/css/chat.css ) link, but i cant find that call on my localhost project. If anyone know solution i would appreciate.
<script src="{{ asset('/js/webflow.js') }}"></script>
<script>
var botmanWidget = {
title:'Scarletbot',
introMessage: 'Hello, I am a Scarlet! I am here to assist you and answer all your questions about our products and services!',
mainColor:'#c02026',
aboutText:'',
bubbleBackground:'#c02026',
headerTextColor: '#fff',
};
</script>
<script id="botmanWidget" src="{{ asset('/js/widget.js') }}"></script>
You may add frameEndpoint in
var botmanWidget = {
frameEndpoint: '<?php echo base_url('botdemo/chatserver1');?>',
title:'Scarletbot',
introMessage: 'Hello, I am a Scarlet! I am here to assist you and answer all your questions about our products and services!',
mainColor:'#c02026',
aboutText:'',
bubbleBackground:'#c02026',
headerTextColor: '#fff',
};
frameEndpoint is nothing but source of iframe loaded by botman-widget
frameEndpoint source is like :
<!doctype html>
<html>
<head>
<title>BotMan Widget</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/assets/css/chat.min.css">
</head>
<body>
<script id="botmanWidget" src='https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/js/chat.js'></script>
</body>
</html>
Here you may use own css as well.
I quickly checked out the web widget on the botman github.
There is a simple link to the chat.css in the head of chat.html located in the src folder.
This points to assets/css/chat.css, which you can edit freely and add a background-color to.
I use brute force in the iframe to change background with jquery
$(document).on('click', '.desktop-closed-message-avatar img', function() {
var iframe = document.getElementById("chatBotManFrame");
iframe.addEventListener('load', function () {
var htmlFrame = this.contentWindow.document.getElementsByTagName("html")[0];
var bodyFrame = this.contentWindow.document.getElementsByTagName("body")[0];
var headFrame = this.contentWindow.document.getElementsByTagName("head")[0];
var image = "https://images.unsplash.com/photo-1501597301489-8b75b675ba0a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1349&q=80"
htmlFrame.style.backgroundImage = "url("+image+")";
bodyFrame.style.backgroundImage = "url("+image+")";
});
});

Disable external content loading inside iFrame

Is there anyway of disabling loading external content inside of an iFrame?
Imagine there is a an iframe defined like:
<iframe srcdoc="
<html>
<head>
<title>Example Page!</title>
<link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'>
</head>
<body>
<p class='main'>Here goes the text.
</p>
<script src='http://example.com/js/superscript.js'>
</body>
</html>">
</iframe>
The loading of JS can be disabled with the allow-scripts inside of the sanbox attribute, but is there any way of disabling the load of the external css (and other external content)?
If not, is there any replacement for "rendering" html code (for example by JS), which would enable this?
I've made the following function to remove loading some assets from emails displayed in an iframe:
const replaced = []
const h = html
.replace(/url\s*\(([\s\S]+?)\)/g, (m,url) => {
url = url.trim()
try {
url = decodeURIComponent(url)
} catch (err) {/**/}
replaced.push(url)
return 'url()'
})
.replace(/[\s'"](?:src|srcset|background)?\s*=\s*(['"])([^\1]*?)\1/g, (m,q,src) => {
if (!src) return m // empty
replaced.push(src)
return ''
})
.replace(/<\s*link[^>]*?([\s'"]href\s*=\s*(['"])([^\2]*?)\2)/g, (m,attr,q,src) => {
if (!src) return // empty
replaced.push(src)
return m.replace(attr, '')
})
interestingly, <img alt="test"src="http://src.com/img.jpg"> is valid and will be displayed by chrome so whitespace before an attribute is actually not required, so I edited this answer to account for that...
It's probably not perfect, but you can tweak it as you see more cases by adding attributes...
Yes you can achieve it by using src not srcdoc and prefixing with data:text/html;charset=UTF-8,.
In your example:
<iframe src="data:text/html;charset=UTF-8,<html> <head> <title>Example Page!</title> <link rel='stylesheet' type='text/css' href='http://example.com/mystyle.css'> </head> <body> <p class='main'>Here goes the text. </p><script src='http://example.com/js/superscript.js'> </body> </html>">
</iframe>

What's wrong with this code? It's doing nothing

<HTML>
<HEAD>
<script>
$(function(){
$(window).on('hashchange', function() {
var hash = location.hash.replace( /^#/, '' );
document.title = 'example ' + hash;
});
$(window).trigger('hashchange');
});
</script>
<TITLE>example</TITLE>
</HEAD>
<BODY>
</body>
</HTML>
Let's say the <title> of example.com is example
This code should automatically update the page title for example.com/#city1 to example city1 and example.com/#city2 to example city2 and so on.
I have only an index.html file and I don't want to add php file to my html file.
As said in the comments you need to add the jQuery library to your page using :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
Then your code should work as expected.

Evaluate JavaScript code using PhantomJS

I'm trying to use PhantomJS to run some JavaScript from an ad server and parse out the response object for information about the ad that was served. This is readily available from Firefox/Chrome Dev Tools, but I need to access that same information from a server. I can get Phantom to run, but as soon as I try to include external JS page.includeJs("http://www.someadserver.com/config.js?nwid=1909"and access variables that are set via that external JS someadserver.setup({ domain: 'http://www.someadserver.com'}); it fails miserably. Any help would be greatly appreciated.
"use strict";
var page = require('webpage').create();
page.content = `
<html>
<head>
<script>
someadserver.setup({ domain: 'http://www.someadserver.com'});
</script>
<title>The title of the web page.</title>
</head>
<body>
<div class="ads_leaderboard">
<!-- position: leaderboard -->
<script>
someadserver.call( "std" , {
siteId: 100806,
pageId: 656377,
target: ""
});
</script>
</div>
<div id="foo">this is foo</div>
</body>
</html>`;
var title = page.evaluate(function (s) {
page.includeJs(
"http://www.someadserver.com/config.js?nwid=1909",
function() {
return document.querySelector(s).innerText;
}, 'title');
});
console.log(title);
phantom.exit(1);
EDIT 1:
I've simplified my script (below) and I'm clearly missing something. When I run the script below using bin/phantomjs /srv/phantom_test.js the only output I get is end page. Why aren't the rest of the console.log statements executing?
"use strict";
var page = require('webpage').create();
page.content = "<html>" +
"<head>" +
" <title>The title of the web page.</title>" +
"</head>" +
"<body>" +
"<div id=\"foo\">this is foo</div>" +
"</body>" +
"</html>";
page.includeJs("http://www.someadserver.com/config.js?nwid=1909", function() {
console.log('start function');
var title = page.evaluate(function(s){
return document.querySelector(s).innerText;
}, 'title');
console.log(title);
console.log('end function');
});
console.log('end page');
phantom.exit();
The stuff inside page.evaluate is executed in the context of a target page as if that code was inside of that page.
page.includeJS(...) will not be a valid code on a someadserver.com.
The correct way is vice versa:
page.includeJs("http://www.someadserver.com/config.js?nwid=1909", function() {
var title = page.evaluate(function(s){
return document.querySelector(s).innerText;
}, 'title');
});
Your first snippet doesn't work, because assigning a value to page.content immediately executes it. So, someadserver.setup(...) is executed immediately as if the page is actually loaded, but at this time the page.includeJs(...) call hasn't happened yet.
You should be able to actually include script that you want to run inside of the page source:
var content = `
<html>
<head>
<script src="http://www.someadserver.com/config.js?nwid=1909"></script>
<script>
someadserver.setup({ domain: 'http://www.someadserver.com'});
</script>
<title>The title of the web page.</title>
</head>
<body>
<div class="ads_leaderboard">
<!-- position: leaderboard -->
<script>
someadserver.call( "std" , {
siteId: 100806,
pageId: 656377,
target: ""
});
</script>
</div>
<div id="foo">this is foo</div>
</body>
</html>`;
page.setContent(content, "http://www.someadserver.com/");
var title = page.evaluate(function (s) {
return document.querySelector(s).innerText;
}, 'title');
console.log(title);
phantom.exit();
I've also used page.setContent in order to set the domain, so that further script loading is not broken. When a page source is assigned to page.content, the default URL is actually about:blank and you don't want that.
Further problems with your first snippet:
The beginnings and ends of page.evaluate and page.includeJs don't match up!
There is no page inside of page.evaluate, because the page context is sandboxed!
Your second snippet doesn't work, because page.includeJs(...) is a asynchronous function (it has a callback!), so you're exiting the script too early.

How to create a simple Loading CSS that shows "loading" right at the first time the page got loaded & clear it after the page finished loading?

I am using Java script with GWTP technology to build my app.
Ok, I have a requirement. I want to use loading CSS to show the loading information right at the first time the page got loaded. The loading must show before any javascript files begin to be downloaded.
After all javascript files got downloaded, the loading CSS should stop working.
For example, when people visit mydomain.com, it should show "..loading..." indicator in the middle of the page & after the page starts to be visible, then it should hide the loading indicator.
The structure of my Ajax page is as following.
<html>
<head>
<meta>...</meta>
<link type="text/css" rel="stylesheet" href="myCss.css">
<script type="text/javascript" language="javascript" src="myproject.nocache.js"> </script> // this is where the big Javascript file got loaded
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position: absolute; width: 0;height: 0; border: 0;"></iframe>
</body>
</html>
Can you not just use the "onload" attribute of the body tag?
Put this javascript line to make the "loading" disappear at the end of the large javascript file :
document.getElementById('loading').className='loaded';
<!DOCTYPE HTML>
<html>
<head>
<meta>...</meta>
<link type="text/css" rel="stylesheet" href="myCss.css">
</head>
<script>
function pageLoaded(){
var jsFile=document.createElement('script');
jsFile.setAttribute("type","text/javascript");
jsFile.setAttribute("src", 'myproject.nocache.js');
document.getElementsByTagName("head")[0].appendChild(jsFile);
}
</script>
<style>
html{width:100%;height:100%;}
body{width:100%;height:100%;margin:0px;position:relative;}
div#loading{display:table;width:100%;height:100%;position:absolute;top:0px;left:0px;}
div#loading div{display:table-cell;width:100%;height:100%;text-align:center;vertical-align:middle;background-color:#cccccc;}
div.loaded#loading{display:none;}
</style>
<body onload="pageLoaded();">
<div id="loading">
<div>LOADING...</div>
</div>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position: absolute; width: 0;height: 0; border: 0;"></iframe>
</body>
</html>
Add loading class to body in the HTML code
<body class="no-mobile pc bootstrap loading">
And when all loading of scripts finished remove the loading class of body tag.
window.onload = function () {
$("#body").removeClass('loading');
}
This is just example, You can use pure javascript to remove 'loading' class of body.
Like this
Used body as ID, because I can't put custom body tag there.
(function (w, d, url, resource) {
w.t = new Date().getTime();
if (/webkit/i.test(w.navigator.userAgent)) {
d.write("<style>#loading"
+ "{-webkit-animation:blink"
+ " 350ms linear 0s normal infinite forwards;}"
+ "#-webkit-keyframes blink{"
+ "0%{color:transparent;}100%{color:blue;}};"
+ "</style>");
};
d.write("<div id=loading"
+ " style=font-size:24px;position:relative;"
+ "left:45%;top:25%;-moz-text-blink:blink;>"
+ "loading...</div>");
var script = d.createElement("script");
script.src = url;
script.async = true;
script.type = "text/javascript";
var head = d.getElementsByTagName("head")[0];
head.appendChild(script);
w.s = setInterval(function () {
// check for `object` or `function`, i.e.g., `window.jQuery()`
// set by `script` (`src`), `url`, resource at `window`,
// at `1000ms` intervals , adjustable, e.g., `500`; `250`
if (resource in w
&& typeof w.jQuery() === "object"
&& typeof w.jQuery === "function" ) {
// do stuff
d.body.removeChild(d.getElementById("loading"));
d.write("<span class=status>jQuery version: "
+ jQuery().jquery
+ "\n"
+ "estimated loading time: "
+ Number(new Date().getTime() - w.t)
+ "</span>");
// do stuff
// utilize `object`, `function`, data
// loaded in `window`, `document`,
// from `script`, `url` , resource
$("body")
.append("<br><iframe "
+ "src=http://api.jquery.com "
+ "width=480 height=400></iframe>");
$(".status").fadeOut(5000, function() {
$(".status", this).remove();
});
clearInterval(w.s);
};
}, 1000);
}(window, document, "http://code.jquery.com/jquery-latest.js", "jQuery"));
jsfiddle http://jsfiddle.net/guest271314/27RTx/

Categories