I have a WinJS project and I receive toasts notification from my webservice. In my webservice my XML is like:
string type = "Computer";
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string message = "{\"Message\":{\"Id\":\"6724d22a-87fe-4137-b501-9d9a9a0558b1\",\"DetailId\":\"dc02e784-7832-4625-a538-29be7f885ccb\",\"Description\":\" Message\",\"UserName\":null,\"ActionDateTime\":\"2015-09-15T15:36:14+05:45\",\"CalamityId\":\"c0fa848e-ee6c-4b91-8391-a12058f25387\",\"UseConferenceCalls\":true,\"IsActionCompleted\":false},\"Type\":\"COmp\"}";
string toast2 = string.Format(#"<toast launch= '{0}'>
<visual version='1'>
<binding template='ToastText04'>
<text id='1'>{1}</text>
<text id='2'>{2}</text>
</binding>
</visual>
</toast>", message, "Alert", type);
string xml = toast1 + toast2;
I want to navigate to a specific html page with the useful json as parameters when user click on toasts. Please suggest me some ways to do this.
Currently I have implemented the following function to handle my toasts.This only works when the app is in active state i.e. running in foreground or background. But when the app is closed completely this function won't hit and failed to meet my requirement.
WinJS.Application.addEventListener("activated", onActivatedHandler, true);
function onActivatedHandler(args) {
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
var messageDetails = (args.detail.arguments).replace(/\\/g, '');
PhonegapService.setNotificationMessage(messageDetails, function () {
window.location.href = "page3.html";
});
}
}
I was facing a similar issue. In my case I was calling functions even before cordova deviceready was fired. From your question not sure if yours is a cordova app or not but make sure all the required javascript files are loaded. You can execute your logic once document is ready. I assume you are using jquery.
function onActivatedHandler(args) {
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
$(document).ready(function(){
var messageDetails = (args.detail.arguments).replace(/\\/g, '');
PhonegapService.setNotificationMessage(messageDetails, function () {
window.location.href = "page3.html";
});
});
}
}
Related
This is my first question on stackoverflow.
I want to load a different page in a certain space of my homepage. I tried it with JavaScript many times but hitting a wall. I can do it with iframe. But I was thinking if there is any other way to do it. And I want to load the page when the user clicks the link.
The way I did it is like this:
document.getElementById('aboutUs').onclick = function() {
document.getElementById('newDiv').style.display = "none";
document.getElementById('iFrame').style.display = "block";
}
Thank You!!!
You need to make request to load the static content.
Hope this snippet will be useful
//A generic function to load the static page
function loadContent(target, staticPageLoc) {
var r = new XMLHttpRequest(); // making request to load the static page
r.open("GET", staticPageLoc, true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
target.innerHTML = ""; // removing any previous content
target.innerHTML = r.responseText; // response will be the static page
};
r.send();
}
document.getElementById('aboutUs').onclick = function() {
loadContent(document.getElementById('id of dom element where page will load'), 'page path')
}
Alternately you can explore jquery.load function & better to run it in a server or else you may come across CORS
I am using sammy.js for single page application in asp.net mvc. Everything is fine, but I am facing one problem which is that I can not reload the page. For example When I am in the dashboard my URL is
http://localhost:1834/#/Home/Index?lblbreadcum=Dashboard
layout.cshtml
<script>
$(function () {
var routing = new Routing('#Url.Content("~/")', '#page', 'welcome');
routing.init();
});
</script>
routing.js
var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) {
var url = hash.replace('#/', '');
if (url === appRoot)
url = defaultRoute;
return url;
}
return {
init: function () {
Sammy(contentSelector, function () {
this.get(/\#\/(.*)/, function (context) {
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run('#/');
}
};
}
I want to reload the page by clicking the dashboard menu/link. But click event not firing because link is not changing. But if I want to go another page then it is fine. Please help me out. Thanks.
I think you have to append the same partial again. You can't "update" the partial in that meaning.
As you say in your post, when you click another link and then back again it works.
That's what you'll have to do. Append the same page/partial again, by doing that you clear all variables and recreate them, by that simulating a refresh.
EDIT: Added example
Observe that I didn't copy your code straight off but I think you'll understand :)
And I don't use hash (#) in my example.
var app = Sammy(function () {
this.get('/', function (context) {
// context is equalient to data.app in the custom bind example
// currentComponent('home'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
this.bind('mycustom-trigger', function (e, data) {
this.redirect('/'); // force redirect
});
this.get('/about', function (evt) {
// currentComponent('about'); I use components in my code but you should be able to swith to your implementation
var url = getUrlFromHash(context.path);
context.load(url).swap();
});
}).run();
// I did an easy example trigger here but I think you will need a trigger on your link-element. Mayby with a conditional check wheter or not to trigger the manually binding or not
$('.navbar-collapse').click(function () {
app.trigger('mycustom-trigger', app);
});
Please read more about events and routing in sammy.js
Good luck :)
An easier and cleaner way to force the route to reload is to call the Sammy.Application refresh() method:
import { sammyApp } from '../mySammyApp';
const url = `${mySearchRoute}/${encodeURIComponent(this.state.searchText)}`;
if (window.location.hash === url) {
sammyApp.refresh();
else {
window.location.hash = url;
}
I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});
i'm trying to login into the site with the following javascript. But, i'm loading only the complete page. I'm developing windows 8 app
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
document.getElementById("bt_login").addEventListener("click", login, false);
}
});
})();
function login() {
var xhrDiv = document.getElementById("xhrReport");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = dataLoaded;
xhr.open("POST", "http://www.160by2.com", true, <username>, <password>);
xhr.send();
function dataLoaded() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// OK
xhrDiv.innerHTML = window.toStaticHTML("response:" + xhr.responseText);
} else {
// not OK
xhrDiv.innerText = "failure";
}
}
};}
I want to dsiplay in xhrdiv.innerHTML as "LOGIN SUCCESS" or "LOGIN ERROR"
EDIT:
I tried the following code:
iframe = document.getElementById("ifra_op");
iframe.setAttribute("src", "http://www.160by2.com/index");
document.getElementById("op").appendChild(iframe);
iframe.contentWindow.document.getElementById("MobileNoLogin") = "<mobno>";
iframe.contentWindow.document.getElementById("LoginPassword") = "<pass>;
iframe.contentWindow.document.getElementsByName("LoginForm").click();
But, there is an error. It says "Javascript run time error:math is undefined"
"math" comes from the website. I don't know how to handle this. Also, the permission is denied. Why is that so?
You need to make sure you have a service (something like a web service) in the remote server to process the request.
In here what you can do is.
Create an iframe and set the src to 160by2;
Access the webpage using iframe.contentwindow, inject your code to fill up the forms and trigger the submit button.
Parse the received html to verify your login.
Use jquery , makes life easier.
var iframe = $("#ifra_op");
$(iframe).attr("src", "http://www.160by2.com/index");
$(iframe).attr("onload","submitForm();");
function submitForm(){
$(iframe.contentWindow.document).find("#MobileNoLogin").val("9999");
$(iframe.contentWindow.document).find("#LoginPassword").val("pass");
$('#button').click();
}
I have an EventListener and a function generator.gettext.
Code:
var generator = {
gettext: function (mytext) {
//I send a message which is intercepted by my content script.
//Later my content script will send a reply back which will be processed by 'receiver'
window.postMessage({
type: "MESSAGE",
text: mytext
}, "*");
while (generatedtext == "") {
//WAIT until generatedtext is set by 'receiver'
}
return generator.generatedtext;
},
generatedtext: ""
};
function receiver(event) {
if (event.data.type && (event.data.type == "FROM_CONTENTSCRIPT")) {
generator.generatedtext = event.data.text;
}
}
window.addEventListener('message', receiver, false);
I want that generator.gettext returns generator.generatedtext but I can't make it wait until receiver sets it. I have the impression that the EventListener is locked while generator.gettext is called. I have to change it so it becomes asynchronous and uses a callback parameter, but I'm new into this and don't know how to make it work. Can somebody help me?
EDIT: What I want to do is to process input on a website. There is a Javascript file and I want that input is processed by my content script. I redirected the javascript-file to a modified one on my hard drive. I change a line where the javascript loads the input. When I submit text the Javascript file calls something like var message = generator.gettext(mytext.value); My code above is injected into the page and has to send mytext to my content-script and has to return the output of my content-script.
I think I understand what you're asking, though it isn't very clear.
You are posting a message and you want to store the result on generator.generatedtext. You are already doing so.
var generator = {
generatedtext:'',
gettext: function (mytext) {
window.postMessage({
type: "MESSAGE",
text: mytext
}, "*");
}
};
window.addEventListener('message', function(ev){
if (event.data.type && (event.data.type == "FROM_CONTENTSCRIPT")) {
generator.generatedtext = event.data.text;
}
},false);
Unless there is some other usage that you are trying to do but haven't made clear, this is all you need. There is no need to have generator.gettext() return anything, since the message event listener is assigning the messages being received to generator.generatedtext.
If this isn't exactly what you wanted, post a comment with more details and I'll try to help you out.