How to load different pages in O365 mail app based on regex - javascript

I am creating an O365 app and I have 2 .aspx files, when the user clicks on the O365 mail app, I want each of these pages to be loaded based on the subject of the mail.
Scenario 1: Mail subject contains '#'
result: load page1
Scenario 2: Mail subject does not contain '#'
result: load page2
I have tried having an intermediate .js file where I have written the logic,
but when I do window.location = "path_to_aspx_file",
only the html is loaded but the js files do not run.
My current implementation:
I have LandingLogic.js
(function () {
"use strict";
//The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var sub = item.subject;
if (sub.indexOf("some text") > -1) {
window.location = "http://localhost:51776/File1.aspx";
}
else {
window.location = "http://localhost:51776/File2.aspx";
}
});
};
})();
After a bit of fumbling around.
I am able to navigate to each of these files now, but I am not sure how to access the mail subject from File1.aspx and File2.aspx.

Did you initialize the Office context before you using Office JavaScript API to get the subject? To redirect the HTML page easily, we can include the JavaScript like below:
Home.js:
/// <reference path="../App.js" />
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
RedirectHTMLPage();
});
};
function RedirectHTMLPage() {
var subject = Office.context.mailbox.item.subject;
if (subject.indexOf("#") != -1) {
window.location.href = "https://localhost:44300/page1.aspx";
} else {
window.location.href = "https://localhost:44300/page2.aspx";
}
}
})();
The HTML page for redirecting:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title></title>
<script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<!-- To enable offline debugging using a local reference to Office.js, use: -->
<!-- <script src="../../Scripts/Office/MicrosoftAjax.js" type="text/javascript"></script> -->
<!-- <script src="../../Scripts/Office/1/office.js" type="text/javascript"></script> -->
<link href="../App.css" rel="stylesheet" type="text/css" />
<script src="../App.js" type="text/javascript"></script>
<link href="Home.css" rel="stylesheet" type="text/css" />
<script src="Home.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
I have tried having an intermediate .js file where I have written the logic, but when I do window.load = "path_to_aspx_file", only the html is loaded but the js files do not run.
Would you mind sharing the detail you using the “window.load”?

Fei Xue answer is correct . if you want to get subject from file2.aspx , add office.js reference and access subject same as file1.aspx inside the Office.initialize event
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>

Related

JavaScript: Read directory from within addEventListener function

I added an event listener to my website which should add a date, time and device-id to the website. These information are included in the filenames of some files located in a directory at the same level as my index.html.
Directory Structure:
- audiofiles
-- date_time_device.wav
-- date2_time2_device2.wav
- scripts
-- scripts.js
- Home.html
Within the head of Home.html I'm calling a addContent() (located in scripts.js) which includes the addEventListener().
This works if I'm inserting hardcoded strings, so it seems that reading from the directory does not work.
It would be great if anybody could steer me into the right direction. Thanks!
Head of Home.html:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/wavesurfer.js"></script>
<script type="text/javascript" src='scripts/scripts.js'> </script>
<script type="text/javascript" src="js/wavesurfer.js"></script>
<script>
addContent();
</script>
<title>Home</title>
</head>
scripts.js:
function addContent() {
document.addEventListener("DOMContentLoaded", function(event) {
var fs = require('fs');
const files = fs.readdirSync('path/to/audiofiles');
for (i=0;i<3;i++) {
var date = files[i].slice(0,10);
var time = files[i].slice(11,19);
var device = files[i].slice(20,-4);
var TheInnerHTML ="";
TheInnerHTML += "<tr><td> blabla" + 3 + " " + String(date)+"</td><td>"+String(time)+"</td></tr>"+String(device)+"</td></tr><br>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;
});
}

Recording State of iframe(url) from within an Office Add-in

So I am developing an office add in which will essentially contain an iframe which will be running an application we own.
The problem is, I want to contantly record the url of the iframe so that i can save this to the addin state, aloowing us to use that information to load the iframe to the correct url each time the addin is reopened.
I cant figure out a way to output the url from within the iframe each time it changes? here is a sample of what i have, this doesnt contain the application just a couple of sample pages:
Home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title></title>
<script src="../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="../Scripts/FabricUI/MessageBanner.js" type="text/javascript"></script>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<link href="Home.css" rel="stylesheet" type="text/css" />
<script src="Home.js" type="text/javascript"></script>
<!-- For the Office UI Fabric, go to https://aka.ms/office-ui-fabric to learn more. -->
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.min.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.components.min.css">
</head>
<body>
</body>
</html>
Home.js
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
var iframew = document.createElement('iframe');
iframew.src = '../SecondPage/SecondPage.html';
iframew.id = 'iframe1';
iframew.onload = iframeLoaded(this.contentWindow.location.href);
document.body.appendChild(iframew);
});
};
// Helper function for displaying notifications
function iframeLoaded(location) {
console.log("log", location);
}
})();
Cant understand why people are downvoting this question, it was a genuine issue
Anyway, for anyone interested I solved this by attaching a a function after the iframe loads which outputs the url of the iframe at set interval periods
var iframew = document.createElement('iframe');
iframew.id = 'iframe1';
var baseUrl = '#YOUR BASE URL#';
let openUrl = getProperty('openurl');
if (!openUrl) {
console.log('No saved url');
iframew.src = baseUrl;
}
else {
console.log('saved url');
console.log(openUrl);
iframew.src = openUrl;
}
//when iframe loads attach function to save at interval
iframew.addEventListener('load', function () { setInterval(function () { iframeLoaded(iframew.contentWindow.location.hash, iframew.contentWindow.location.href); }, 4000); });
document.body.appendChild(iframew);
here is the iframeLoaded Function which also does some manipulation of the url and calles another function which saves the url to the doocument settings of the add-in:
function iframeLoaded(hash, location) {
//if not in an analysis dont save
if (hash.indexOf('#/dataset/') !== -1 ) {
console.log("Same url")
return
}
//remove # from hash
hash = hash.substr(1);
//concatenate base and hash
let newUrl = baseUrl + hash;
console.log(hash)
console.log(newUrl);
//save
if (Office.context.document.settings) {
saveProperty('openurl', newUrl);
}
}

JavaScript does not work on pages other than my MasterPage and pages that aren't linked to it

Sorry for the bad english :P
I'm using ASP.NET
I'm trying to use a JavaScript that I've found on the Internet to set masks to my telephone and cellphone text fields, but the JS code just work at the fields that are located at my MasterPage. I don't have much experience with JS (almost none) and I have no idea how to resolve this since there is no error at my Logcat.
I tried to reference it at my MasterPage's head, body and inside the ContentPlaceHolder.
Here is the JS code:
function mascara(o, f) {
v_obj = o
v_fun = f
setTimeout("execmascara()", 1)
}
function execmascara() {
v_obj.value = v_fun(v_obj.value)
}
function mtel(v) {
v = v.replace(/\D/g, "");
v = v.replace(/^(\d{2})(\d)/g, "($1)$2");
v = v.replace(/(\d)(\d{4})$/, "$1-$2");
return v;
}
function id(el) {
return document.getElementById(el);
}
window.onload = function () {
id('txtTelefone').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('txtCelular').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('telefoneContato').onkeypress = function () { //Located at Contact Page - not working
mascara(this, mtel);
}
id('txtCelularUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
id('txtTelefoneUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
}
As I said before I tried to reference my JS file in some places, the codes that I tried were:
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
As you can see, the fields are located in diferent pages, I also tried to put the code directly at the pages but I had no luck.
I think that I don't need to post my entire MasterPage here, then I'll put just the head, but if exists a need I will edit the post.
<head runat="server">
<title></title>
<link rel="shortcut icon" href="../imagens/icone.ico" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<link href="../Componentes/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/fontawesome/css/font-awesome.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/css/MasterPage.css" rel="stylesheet" />
<link href="../Fontes/Fontes.css" rel="stylesheet" />
<script src="../Componentes/bootstrap/js/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/debug.addIndicators.min.js"></script>
<script src="../Componentes/bootstrap/js/bootstrap.min.js"></script>
<%--Mask Scripts--%>
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
EDIT 1
Tried this:
id('<%= txtTelefoneContato.ClientID %>').onkeypress = function () { //Located at Contact Page - Still not working
mascara(this, mtel);
}
id('<%= txtCelularUser.ClientID %>').onkeypress = function () { //Located at User Page - Still not working
mascara(this, mtel);
}
id('<%= txtTelefoneUser.ClientID %>').onkeypress = function () { //Located at User Page- Still not working
mascara(this, mtel);
}
The reference to the script is at MasterPage head. But the problem still the same
EDIT2
Im receiving this when I inspect my page:
Error image 1
Error image 2
Resolved
As VDWWD explained, I just put the JS code directly at the .aspx pages with this modification:
from:,
id('txtCelularUser').onkeypress = function () {
mascara(this, mtel);
}
to:
id('<%= txtCelularUser.ClientID %>').onkeypress = function () {
mascara(this, mtel);
}
Thank you in advance
You have to use it like this when accessing elements with JavaScript that have master pages. And it's also better to use it even without master pages. If you should change the ID in you don't have to change it also in your script.
id('<%= txtTelefoneUser.ClientID %>').onkeypress
If you look at the HTML source you will see that the ID of the element has been changed from txtTelefoneUser to something like this ContentPlaceHolder_txtTelefoneUser. Aspnet adds a prefix to ensure every element has a unique ID.
You will see the same usage of prefix in elements that repeat data like GridView/Repeater/DataList etc.
UPDATE
If you put the javascript in an external file you can put a reference to it on the master page like this (assuming Componentes is a folder in the root):
<script src="/Componentes/js/mascaras.js" type="text/javascript"></script>
However putting <%= txtTelefoneUser.ClientID %> in an external file will not work, only on an .aspx page. To make that work declare those elements as variables an assign them on the aspx page while using them in the external js file.
Below a demo:
In the external javascript file:
var myElement;
function myFunction() {
myElement.value = "Success!";
}
and then on the .aspx page:
<script type="text/javascript">
myElement = document.getElementById("<%= TextBox1.ClientID %>");
</script>
After a long time I found that the elements that area inside the Content to be found in javascript must have the name of the content ID in front more undeline and the name of the element ID, you are looking for.
example:
document.querySelector("#ContentPlaceHolder1_img1").setAttribute("src", 123);

hi how can help me and resolve "Cordova.exec() is not defined at file:///android_asset/www/plugin.js" error

i was trying to implement a simple push notification application using some plugins. a this moment i have an problem with a javaScript file when i click on a bouton how call a javaScript function called register , that show me an error :
Uncaught ReferenceError: Cordova is not defined at file:///android_asset/www/GCMPlugin.js
this is my GCMPlugin.js
(function () {
var GCM = function() {};
GCM.prototype.register = function(senderID, eventCallback, successCallback, failureCallback) {
if ( typeof eventCallback != "string") { // The eventCallback has to be a STRING name not the actual routine like success/fail routines
var e = new Array();
e.msg = 'eventCallback must be a STRING name of the routine';
e.rc = -1;
failureCallback( e );
return;
}
return Cordova.exec(successCallback,
failureCallback,
'GCMPlugin',
'register',
[{ senderID: senderID, ecb : eventCallback }]);
};
if (cordova.addPlugin) {
cordova.addConstructor(function() {
//Register the javascript plugin with Cordova
cordova.addPlugin('GCM', new GCM());
});
} else {
if (!window.plugins) {
window.plugins = {};
}
window.plugins.GCM = new GCM();
}
})();
the function register in index.js :
function register()
{ window.plugins.GCM.register("1193127317675", "GCM_Event", GCM_Success, GCM_Fail ); }
this is my index.html :
<!DOCTYPE HTML>
<html>
<head>
<title>M W A</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>
<script src="GCMPlugin.js"></script> <!-- GCM Cordova plugin -->
<script type="text/javascript" charset="utf-8" src="jquery_1.5.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<!-- Include my Javascript routines -->
<script type="text/javascript" charset="utf-8" src="PushNotification.js"></script>
<script type="text/javascript" charset="utf-8" src="CORDOVA_GCM_script.js"></script>
</head>
<body>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<input type="button" value="Register" style="width: 200px; height: 100px;" onclick="register();" >
<input type="button" value="Unregister" style="width: 200px; height: 100px;" onclick="unregister();" >
</body>
</html>
note : that i use cordova-2.1.0.js ! and when i use cordova.js (3.0.0) i get that exec() call to unknown plugin: GCMPlugin
can u help me to resolve this problem .. i spend more than 3 days to resolve it but i still have this problem
Uncaught ReferenceError: Cordova is not defined at file:
Seems you forgot to add cordova js script to your assets folder.
If you want to use GCM, you should do the following:
At first, you should have installed GCM plugin (https://github.com/marknutter/GCM-Cordova).
For cordova 3.0 you just have to add this lines to your res/xml/config.xml file.
<feature name="GCMPlugin">
<param name="android-package" value="com.plugin.GCM.GCMPlugin" />
</feature>
Instead of <plugin name="GCMPlugin" value="com.plugin.GCM.GCMPlugin" />
That's because of <plugin> deprecated in cordova 3.*

Page specific javascripts in Play

I'm building a small application in Play and have an 'outer' template which holds all my CSS and JS imports (jQuery and my main.js file). CSS at the top, JS at the bottom with a body tag in between... pretty basic stuff:
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/foundation.css")">
<link rel="stylesheet" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
</head>
<body>
#content
</body>
<script src='#routes.Assets.at("javascripts/jquery-1.9.0.min.js")' type="text/javascript"></script>
<script src='#routes.Assets.at("javascripts/index.js")' type="text/javascript"> </script>
</html>
Which is fine.
However, I have page specific javascript functions that should run based on what the page is. So if I go to localhost:9000/test, I want a particular set of functions to run.
If I go to localhost:9000/chips, I want another set of functions to run.
I can't see a neat way of doing this, really, except checking the current page url in the script and executing functions based on that... but the routes file is already doing stuff based on the current page url - seems strange to have to do something so similar twice.
One solution is to put all my scripts at the top and then execute inline scripts in the HTML... but I hate doing things like that.
You have very nice and clear sample available in the... documentation.
Scroll to the bottom and check section: moreScripts and moreStyles equivalents, you have there ready to use samples.
I use a ViewModel approach to solve this issue.
The default ViewModel:
class DefaultPage(
implicit val request: RequestHeader,
implicit val lang: Lang) {
var title: String = null
val styles = mutable.LinkedHashMap.empty[String, Int]
val scripts = mutable.LinkedHashMap.empty[String, Int]
def title(title: String) {
this.title = title
}
def style(style: String)(implicit priority: Int = 500) {
styles.put(style, priority)
}
def script(script: String)(implicit priority: Int = 500) {
scripts.put(script.toString, priority)
}
def translate(message: String, objects: Any*) = Messages(message, objects: _*)
}
Then I have two template tags:
styles.scala.html
#(styles: scala.collection.mutable.Map[String, Int])
#for(style <- styles.toList.sortBy(_._2)) {
<link rel="stylesheet" href="#routes.Assets.at(style._1)" />
}
scripts.scala.html
#(scripts: scala.collection.mutable.Map[String, Int])
#for(script <- scripts.toList.sortBy(_._2)) {
<script async="true" src="#routes.Assets.at(script._1)"></script>
}
My main template:
main.scala.html
#(page: util.view.models.DefaultPage)(content: Html)
#import tags.scripts
#import tags.styles
#page.style("css/vendor/normalize.min.css")(1)
#page.style("css/vendor/formalize.min.css")(1)
#page.style("css/sprites.min.css")(1)
#page.style("css/main.min.css")(1)
#page.style("css/quirks.min.css")(1000)
#page.script("js/vendor/jquery-1.9.1.min.js")(1)
#page.script("js/vendor/jquery.formalize.min.js")(1)
#page.script("js/plugins.min.js")(1)
#page.script("js/main.min.js")(1)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#page.title</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
#styles(page.styles)
<script src="#routes.Assets.at("js/vendor/modernizr-2.6.2.min.js")"></script>
</head>
<body class="#page.lang.code #page.lang.language #page.lang.country">
#content
#scripts(page.scripts)
</body>
And a sub template:
#(page: util.view.models.ContactUsPage)
#page.title(page.translate("contact.us.title"))
#page.style("css/contact-us.min.css")
#page.script("js/vendor/jquery.expandable-1.1.4.js")
#page.script("js/contact-us.min.js")
#main(page) {
}
You can pass your javascript which is specific to a page as template parameter link

Categories