Perform a function based on the hash with director.js - javascript

I am trying to use director.js for the routing on my single page application. The issue is when you go to a page by typing it into the address bar the application does not perform the function that the hash in the routing table is pointed to.
Here is the example on github - If I refresh the page with a hash or direct to a page with a hash nothing shows up in the console. But if I click on one of the links console output is shown. How can I change this code so that if a user directly goes to a link the routing table checks the hash and performs it's matching function from the routing table? Please answer with a methodology that utilizes director.js
<html>
<head>
<meta charset="utf-8">
<title>A Gentle Introduction</title>
<script src="https://raw.github.com/flatiron/director/master/build/director.min.js"></script>
<script>
var author = function () { console.log("author"); },
books = function () { console.log("books"); },
viewBook = function(bookId) { console.log("viewBook: bookId is populated: " + bookId); };
var routes = {
'/author': author,
'/books': [books, function() { console.log("An inline route handler."); }],
'/books/view/:bookId': viewBook
};
var router = Router(routes);
router.init();
</script>
</head>
<body>
<ul>
<li>#/author</li>
<li>#/books</li>
<li>#/books/view/1</li>
</ul>
</body>
</html>

I have not used Director but your issue may be the fact that GitHub serves the "raw" files with a mime type of "text/plain". So the Director js code might not be processed as javascript, causing your test page not to work. Try downloading your own copy of Director and link to the local version instead of the one on GitHub.

Related

script not loading after navigate from one page to another page nunjucks

i am creating website using nunjucks and express, its king of blog website and content coming from prismic. i want to load one script file for active campane form when user navigate from blog list page to any blog detail page, after navigate to detail page. will get script URL from prismic and I want to execute that script in HTML file.
its working while refresh the detail page but its not working when navigate from one page to another pages.
here is some sample code of my website
---
layout: _layout.njk
permalink: "/{{ post.blogType }}/{{ post.uid }}/"
pagination:
alias: post
data: posts
size: 1
addAllPagesToCollections: true
---
{% set params = item.primary.sumo_form_id.split("=") %}
<div class="_form_{{params[1]}}">
</div>
<script src="{{item.primary.sumo_form_id}}" type="text/javascript" charset="utf-8" defer>
</script>
After spent so much time i have found the solution. it is not proper solution but it is working right now.
Page where you are using recapcha. (njk file)
<div
id="recaptcha"
data-callback="recaptchaOnload"
data-sitekey="SITE_KEY"
data-size="invisible"
class="g-recaptcha">
</div>
index.njk
<head>
<script>
setInterval(()=>{
recaptchaOnload(); // function calls every 20 Seconds.
}, 20000)
function recaptchaOnload() {
try {
if (document.getElementsByClassName("g-recaptcha").length > 0) {
// Whenever route changes this function is going to check for id="g-recaptcha".
// if its found recapcha code renders
grecaptcha.render("recaptcha", {
sitekey: "SITE_KEY",
callback: function () {
console.log("recaptcha callback");
},
});
}
} catch (e) {
return;
}
}
</script>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit' async defer>
</head>
Q - Why i have to use this functionality ?
A - nunjucks are server side templates. so once they are initialised in front-end and if we have added scripts in other than parent route it is not going to initialised, if we changed to new page without redirect(page refresh). So in such conditions this is going to useful

Loading a html script from a typescript file

Im am currenlty working on a integration of a nps widget within a Chatbot. I cannot show you all the code, but i imported the html file inside the chat.ts file. I want to call the entire html file after a button press from the chatbot. I have tried a lot, but nothing seems to help.
this is the chat.ts code (small part of it)
private showAskNicely() {
// #ts-ignore
window.location.assign('npshtml.html');
}
private askNicelyButton() {
const el = document.getElementById('detractbut');
el.addEventListener('click', this.showAskNicely);
}
this is the npshtml file
<html>
<body id="try">
<p>
AskNicely Web Survey Popup Example for traditional websites.<br>
Running in 'force' mode.<br>
Responses will be recorded.
</p>
<script type="text/javascript" src="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.js"></script>
<link href="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.css" rel="stylesheet" type="text/css" charset="utf-8">
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
askNicelyConversation({
config: {
--- cannot show this part ---
},
customData: {
a_custom_property: 'business', // Optional - Send extra data about this customer for reporting and leaderboards
another_custom_property: 'New York' // Optional - Send extra data about this customer for reporting and leaderboards
}
});
});
</script>
</body>
</html>
I also have the button rendered inside another html file with css, but that all works fine.
I have it currently on windows.location.assign, so that it opens a new page. It would be ideal if the script could be triggered without opening a new page.
Using jquery.load does not work and does not give me a error of some sort.

How do I use the Tableau Javascript API to embed dashboards in a webpage for dashboards hosted in Tableau Online?

I am trying to recreate the example provided by Tableau here with a dashboard that is hosted in Tableau Online. A separate article from Tableau talks about modifying the URL of the JS API based on where the dashboard is hosted, which I've tried to follow.
Even though the resulting embed should require a login to be displayed, I expect that login to be displayed in that embedded output/iframe on my webpage. Please refer to the included code. Instead, I'm getting a CORS error:
Refused to display 'https://10ay.online.tableau.com/site/jpl/views/JPLDashboard_V05_JUE/Awareness?:iid=2&:size=800,700&:embed=y&:showVizHome=n&:bootstrapWhenNotified=y&:tabs=n&:apiID=host0#navType=1&navSrc=Parse' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
Is the approach I'm taking correct? If embedding Tableau Online dashboards is possible with their JS API, how do I avoid the CORS error?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JPL Dashboard</title>
<script type="text/javascript" src="https://online.tableau.com/javascripts/api/tableau-2.min.js"></script>
<script type="text/javascript">
function initViz() {
var containerDiv = document.getElementById("vizContainer"),
//url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms",
url = "https://10ay.online.tableau.com/site/jpl/views/JPLDashboard_V05_JUE/Awareness?:iid=2",
options = {
hideTabs: true,
onFirstInteractive: function() {
console.log("Run this code when the viz has finished loading.");
}
};
var viz = new tableau.Viz(containerDiv, url, options);
}
</script>
</head>
<body>
<div id="vizContainer" style="width:800px; height:700px;"></div>
<script type="text/javascript">
(function () {
window.onload = function () {
initViz();
};
})();
</script>
</body>
</html>
Ensure that the URL used for embedding the view is from the Share option in Tableau Online:
In Tableau Online, navigate to the view encountering the problem.
Click the Share button.
Copy the URL link within the Link section.
Configure the embed code to use this URL rather than the Tableau Online URL in the browser address bar.
If it is correct, try to add: <meta http-equiv="X-Frame-Options" content="allow"> in the HTML header
I hope it is helpful,
Gigi

Refresh using Page.js gives 404 Not Found

I have just started using page.js, a routing library that I intend to use to make a single page application with handlebars. I will use the routes to call different handlebar templates. So far, this functionality is working and is as quick as I had hoped.
I am currently encountering an issue where refreshing the page (pressing F5) or copying the URL, and pasting it into a new tab gives me a 404 not found error. It is not calling the not found page that I created in my app.
The code below is a copy of: https://github.com/visionmedia/page.js/tree/master/examples/notfound
<!DOCTYPE html>
<html>
<head>
<title>Not Found</title>
<script src="/page.js"></script>
</head>
<body>
<h1>Not Found</h1>
<p></p>
<ul>
<li>/</li>
<li>/about</li>
<li>/contact</li>
<li>/not-found</li>
</ul>
<script>
page.base('/notfound');
page('/', index);
page('/about', about);
page('/contact', contact);
page('*', notfound);
page();
function index() {
document.querySelector('p')
.textContent = 'viewing index';
}
function about() {
document.querySelector('p')
.textContent = 'viewing about';
}
function contact() {
document.querySelector('p')
.textContent = 'viewing contact';
}
function notfound() {
document.querySelector('p')
.textContent = 'not found';
}
</script>
</body>
When I refresh this page, I am presented with my localhost's 404 page. I get the same result when I use the link http://127.0.0.1/notfound/about.
My question is this: does page.js support refreshing the browser, or using links to access specific portions of my application?
It seems that the question I should really be asking is this: Would it be possible for the web server to redirect all navigation to the page that loads the application? The answer is Yes.
It seems that refreshing the browser would be a common case. An acceptable solution to this would also be to catch any refresh attempts, and redirect them to the main page. Using links to access specific portions of my application is not as crucial, but would be a nice touch.

Problems with SkyScanner Widget in webpage

I am following this example to include a SkyScanner widget on my website:
http://business.skyscanner.net/portal/en-GB/Documentation/Widgets
For some reason I just get an empty div - could this be something to do with the key? When I clicked on the activation link I got from SkyScanner for the widget key, I got a page saying the following:
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be
viewable on remote machines, please create a tag within
a "web.config" configuration file located in the root directory of the
current web application. This tag should then have its
"mode" attribute set to "Off".
I have created a web.config file with the following code:
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
I've had a look at 'inspect element' on Chrome and get the error
Uncaught TypeError: Object # has no method 'write'
api.ashx?key=[KEY]:1
This is the JS:
var API_KEY = 'b7290ac3-1f9f-4575-88a7-89fed0c61f7f',
MAIN_URL = 'http://api.skyscanner.net/api.ashx?key=' + API_KEY;
function main(){
console.log('loaded module');
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
};
function newWrite(str) {
$(str).appendTo('body');
}
var oldWrite = document.write;
document.write = newWrite;
function onMainSkyscannerScriptLoad(e) {
console.log('loaded main script');
skyscanner.loadAndWait('snippets', '1', {'nocss' : true}, main);
}
$('button').click(function() {
console.log('getting main script');
$.getScript(MAIN_URL, onMainSkyscannerScriptLoad);
});
I also used this to personalise the widget:
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setColourScheme("classicbluelight");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
Skyscanner B2B support engineer here. Are you still having trouble with this?
For the quickest response, please contact us here: http://business.skyscanner.net/portal/en-GB/Home/Contact
The first thing to check is that the file is on a web server (localhost is fine), and not loaded from the desktop (or local disk in general). This is because some of the Skyscanner JS code looks up other files using URLs like //api.skyscanner.net. In other words, saving the file to the desktop and opening it from there will not work (will show as an empty div). Here's the most basic example of drawing a widget. Can you try putting this in a file and accessing it through a server? If it works we can build on it :)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="//api.skyscanner.net/api.ashx?key=b7290ac3-1f9f-4575-88a7-89fed0c61f7f"></script>
<script type="text/javascript">
skyscanner.load("snippets","2");
function main(){
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setShape("box300x250");
snippet.setCulture("en-GB");
snippet.setCurrency("USD");
snippet.setProduct("flights","1");
snippet.setProduct("hotels","2");
snippet.setProduct("carhire","3");
snippet.draw(document.getElementById("snippet_searchpanel"));
}
skyscanner.setOnLoadCallback(main);
</script>
</head>
<body>
<div id="snippet_searchpanel" style="width: auto; height:auto;"></div>
</body>
</html>

Categories