How to retrieve the Query string value from web word instance - ms-word

I'm creating a web add-in for Word targeting Word Online. When a document is opened using Word Online, the URL will contain a file name. I am trying to retrieve that file name.
To retrieve this URL I tried using window.location href, but it is fetching my hosted addin web application URL. Is it possible to get the Word Online URL?
Sample Code :
function getParameterByName(name, url) {
if (!url) url = window.location.search;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

What you should use instead?
You should use Office.js API that's defined here
https://learn.microsoft.com/en-us/javascript/api/office/office.document
Office.context.document.url this should return you something that you can use.
Why didn't your solution work?
Unfortunately this is not possible the way you're trying to implement it due to security requirements around iFrames. Word Online is using an iFrame to host your add-in and accessing the parent window from an iFrame is generally very restricted unless you're specifically allowed.
You can however get the base host url of the parent window by looking into the referrer header, but that's pretty much it. I understand that this is not sufficient for you, which is why I'm recommending to use the Word API.
You can see a bit more documentation below about iFrames:
iFrame spec documentation: https://www.w3.org/TR/2011/WD-html5-20110525/the-iframe-element.html
On getting the url that's loading the frame (the parent URL): https://humanwhocodes.com/blog/2013/04/16/getting-the-url-of-an-iframes-parent/
Some more information on how to communicate between parent and the iFrame using postMessage API if you were whitelisted (which you aren't): https://medium.com/#Farzad_YZ/cross-domain-iframe-parent-communication-403912fff692

Related

Use Login Robox using username only like on reward sites

Hi i know this is probably not the place to ask this but i m stumped at the moment as i cant seem to find any reference or docs relating to working with Roblox. I mean sure they have an auth route etc but nothing detailed. I want to login user using username and give them roblox based on different actions they take on the site like completing surveys etc. Can anyone please give me links to some resources that would come in handy for the particular purpose. Thank you.
Roblox does not support any OAuth systems, but you still can use HttpService:GetAsync() function to get strings/data from web site(if the page in website display that text), the way to keep data that you recieved from url(web page) safe is to store script with HttpService:GetAsync() function in server side(example: RobloxScriptService). You need to allow http requests in your GameSettings -> Security in roblox studio. Script example:
local HttpService = game:GetService("HttpService")
local stringg = HttpService:GetAsync("https://pastebin.com/raw/k7S6Ln9R")
print(string)
--Should outpud data written ot the web page, you can use any web page to store data even your own
The only two things that left is to make your web server rewrite the page, or just use some databases at your web site by placing their url into loadstring() function.
Now you just need to parse the string given by url to use it's data.
The pastebin url that i wrote into loadstring() just an example, you can write whatever you wan, but again you need to parse the data that you got from url, or just convert the string into type of text like on the page, and then just check is they written at url/webpage. Example:
local writtenpass = game.Players["anyplayer"].PlayerGui.TestGui.Frame.PasswordTextBox.text
local writtenlogin = game.Players["anyplayer"].PlayerGui.TestGui.Frame.LoginTextBox.text
local HttpService = game:GetService("HttpService")
local response = HttpService:GetAsync("https://pastebin.com/raw/k7S6Ln9R")
local istrue = string.find(response, "{ login = ".. writtenlogin .." pass = ".. writtenpass .." }")
print(istrue)
if istrue == 1 then
print("exist!")
--whatewer actions if login and pass exist
end
You can wiew the page here https://pastebin.com/raw/k7S6Ln9R
Well that a lot of damage!
If it helps mark me

SharePoint Online: Redirect URIs for multi-site environment

We have a multi-site environment where each site has its own redirect URL. We want to use a single Client ID and Secret for our application but register multiple redirect URIs to it. Is it possible to add multiple URLs in below registration form:
I don't think there is possible solution to add on multiple URLs on the SharePoint online app registration form.
But from what i understand there is another way to achieve use a single Client ID and Secret for application and perform multiple redirects.
You can control the redirect url using the appredirect.aspx by specifying the redirect_uri parameter if you need to redirect from the default one check here for reference.
Basiclly it call the subsite page containing the below JS to install the app.
var url = String.format(
"{0}/_layouts/15/appredirect.aspx?client_id={1}&redirect_uri=https://***.azurewebsites.net/<<controller>>/<<view method containing the code to install the app>>?{{StandardTokens}}",
<<subsite url>>, "<<client id>>");
window.location.href = url;
The above javascript calls the appredirect.aspx page which then calls the app site as below,
https://****.azurewebsites.net/home?SPHostUrl=<<subsiteurl>>&SPLanguage=en-US&SPClientTag=1&SPProductNumber=**&SPAppWebUrl=<<weburl>>
Note: The above can be extended to check for the successful installation of the app and display an error message accordingly.
SPWeb.LoadAndInstallWeb equivalent REST / Javascript CSOM is also available here.
Here are some relevant links:
Use the redirect URL in an add-in that asks for permissions on the fly
Redirect URIs and a sample redirect page

Tracking Clicks in Emails to 3rd Party Websites

A hopefully simple GA newbie question.
I programmatically (in Java) send emails to my clients and I'm trying to track what links in the email they click.
The links in the emails are to third party websites.
Is there a way to setup the href links so that I can track what uid's are clicking and treat clicking those links as an event?
An example link would be to a piece of legislation:
https://www.cga.ct.gov/asp/cgabillstatus/cgabillstatus.asp?selBillType=Bill&which_year=2017&bill_num=5210
how would I add that link in the email HTML?
That does not work, at least not with additional resources.
Google Analytics tracks links by sending a request to the Google servers before the user is redirected to the link href. In web tracking this is usually done via a javascript event handler that is attached to the link. In e-mail javascript is not really an option, so that does not work.
What is usually done instead is that in your emails you link to your own server; there is a script that collects the data from the link, and only then it redirects to the originally requested url. Most commercial newsletter packages integrate a solution like that, but you can set up something yourself with some basic programming skills and the Google Analytics measurement protocol (which would allow you to send tracking calls from a server-side redirection script).
Setup the Redirects Tracking Engine
The Redirects Tracking Engine makes it easy to collect event data where traditional tracking methods may not have been possible. This tracking engine utilizes Google Tag Manager and Google Analytics to capture events and is run on the client side. All events can be seen in Google Analytics (Behavior > Events > Top Events).
Getting Started
Installation
Add the latest JQuery and Redirects Tracking Engine scripts to the header of your site.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script type="text/javascript">// Fetches redirects.txt and stores information in the variable data
$.get('redirects.txt', function(data) {
// Fetches the parameters of the query string and stores the path in urlParams
var urlParams = [];
// Sifts through the string and removes unwanted characters
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, '')); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
// Pulls properties from urlParams and stores them in destination array
var destination = Object.keys(urlParams).map(function(path){return urlParams[path]});
// Assigns the redirects.txt data to the userData array
var userData = data.split('\n');
// Multidimensional array declaration
var redirects = [];
// Fetches the total number of objects in the userData array
var total = userData.length;
// Counter variable
var i = 0;
// Runs through the redirects array to check to see if there is a string match
while (i < total) {
// Places userData into the multidimensional redirects array
redirects[i] = userData[i].split(' => ');
// Checks for a path match in the redirects array
if (redirects[i][0] == destination[1]) {
window.location.href = redirects[i][1];
return;
}
i++;
}
// Redirects to safe page if no match is found
window.location.href = 'https://example.com';
});
Setup Google Tag Manager
Paste this code as high in the <head> of the page as possible. Make sure to substitute the filler GTM-XXXX with your Google Tag Manager Account ID.
<!-- Google Tag Manager --><script>(function(w,d,s,l,i){w[l]=w[l]|| [];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js? id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->
Additionally, paste this code immediately after the opening <body> tag. Make sure to substitute the filler GTM-XXXX with your Google Tag Manager Account ID here as well.
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
NOTE: For more information about installing the Google Tag Manager snippet, check out their Quick Start Guide.
Create Tags/Triggers/Variables
Create a variable — You will need to first create a User-Defined Variable. Go to the Variables page of your Google Tag Manager and in the User-Defined Variables section create a new variable named Tracking ID. Give this variable your Google Analytics Tracking ID in the Value field and SAVE.
Create a tag — You will need to go to the Tags page in Google Tag Manager and click the NEW button. Fill in the fields and click SAVE when finished.
Create a trigger — Finally, you will need to create a trigger. Go to the Triggers page in Google Tag Manager. Once there click on the NEW button and fill in the fields and click SAVE when finished.
After these configurations have been setup in Google Tag Manager you are ready to add your redirects to the redirects.txt file.
Redirects
To add a redirect open the redirects.txt file. The text linkedin is telling the engine what path it needs to look for in the URL. Immediately following is the separator => which shows the engine where the assigned path should direct the user. New redirects can be added on a new line and there are no limits to the number of redirects that can be added to this file.
// Example Redirect
linkedin => https://example.com
Failsafe
In the off-chance that one of the redirects is not working it is good to have a page that the user can be directed to. You can add in your failsafe page by modifying the window.location.href location that comes immediately after the loop.
// Redirects to safe page if no match is found
window.location.href = 'https://example.com';
Browser Support
Supported Browsers : Chrome, Firefox, Safari, Opera, Edge, IE7+.
The source code as well as an example can be found on GitHub.

URL fragment lost as part of SAML token authentication; workaround / standard pattern?

Several web application authentication protocols (like WS-Federation and the SAML protocol, i.e., so-called 'passive' protocols, and apparently also ASP.NET Forms authentication, see this StackOverflow question, and AppEngine, see this GWT bug comment) lose the original 'URL fragment', i.e. the part after the #-sign.
What happens is roughly the following: in a clean browser (so no cached info/cookies/login information) I open URL (1) http://example.com/myapp/somepage?some=parameter#somewhere. This makes the browser request (2) http://example.com/myapp/somepage?some=parameter, the server redirects me to my identity provider (including URL (2) in the authentication request), and ultimately I'm redirected back to where I came from, which is URL (2): that is the only URL that the server knows about. But I wanted to go to URL (1), and the URL fragment ('anchor') has been lost along the way, actually in the first step already.
This seems to be a fundamental limitation of these protocols, since the server never sees the URL fragment at all.
I know that it according to specifications that the browser requests (2) from the server, when I navigate to (1), leading to this fragment-losing limitation on the SAML protocol, WS-Federation, etc. My question is: how do I work around this limitation?
The obvious workaround is to avoid URL fragments, as suggested in this answer. However, for our specific web application that is not nice, since we use bookmarkable URL fragments in our single-page GWT application, to make sure that a navigation within our application does not cause the page to reload.
My question: What other workarounds or standard patterns are there for this situation?
(I'm specifically interested in a GWT + SAML protocol solution.)
You basically have two options:
avoid using location.hash (use HTML5's pushState instead, at least on browsers that support it; and/or propose a way to generate permalinks within your app – Google Groups does that)
do the redirection using JavaScript. I.e. instead of sending a redirect from the server, send an empty HTML page with some script that takes the full URL (with the hash) and does the redirection using location.assign() or location.replace(). With a bit of luck (depending on the servers), you'll be redirected to that full URL after authentication.
You can of course do both: if the link is a deep-link into the app, then do the redirect (i.e. assume there's no hash), otherwise send a page with JS to make sure you don't lose any state present in the hash.
And finally the obvious third solution, far from ideal: don't do anything, and try to educate users that when they needed to (re)authenticate then they should re-paste the URL or re-click the link or re-click the bookmark.
According to RFC 1738 anchor tags are not sent by the client to the server, when requesting for a resource.
Anchor tags are used to identify a location within a resource and not a different resource on the server. In order to identify the location in the resource, the client needs to fetch the complete resource from the server, and this process need not involve transfer of information about the fragment (as it does not mean anything to the server).
If you do wish to send the fragment character (#) to the server, then you'll need to encode it in the query string, or the client(browser) will simply ignore that section of the URL when it sends the request to the server.
EDIT:
I don't know any real solution but to work around this issue you need to save your full return URL (with anchor tags) somewhere on the client side, because server don't know anything about anchors. For that you could use SessionStorage (http://www.w3schools.com/html/html5_webstorage.asp) to temporary store ReturnUrl until login process is completed. Please note that it won't be supported on older browsers (like <= IE7).
In that case workaround would look something like this:
<script>
if(typeof(sessionStorage) == 'undefined')
{
sessionStorage = {
getItem: function(){},
setItem: function(){}
};
}
window.onload = function ()
{
var key = 'ReturnUrl';
//try to get last returnUrl with anchors
var returnUrl = sessionStorage.getItem(key);
//if we got something, do the navigation
if(returnUrl !== undefined && returnUrl !== document.URL)
{
//clean it up
sessionStorage.setItem(key, null);
//navigate to last URL
window.location = returnUrl;
}
else
{
//store url
sessionStorage.setItem(key, document.URL);
}
}
</script>
PS. Bear with me if there are some syntax errors because I wrote it down from top of my head and didn't try it.

Fetch and display Google Doc body within html page

Is it possible to retrieve the content of a Google Doc and display it within a div in an html page? If so, what's the right way to implement the "MAGIC" in the stripped-down example below?
<html>
<head>
</head>
<body>
<div>
<MAGIC>
Script or link that retrieves and displays the body of a Google Doc.
</MAGIC>
</div>
</body>
</html>
In the above, you can assume
The html is served by Google Drive Hosting.
The reference to the Google Doc is static.
There is no need to edit the Doc from within the public html page (i.e it's read-only in that context).
I've read through the Apps Script documentation and it looks as though something might be possible with some combination of Document Service and Content Service. For instance, Document Service has getBody() and copy() methods, but it's not clear whether the objects returned by these calls can be rendered WYSIWYG as html for insertion into an html container.
Background: I'm trying to implement a safe easy-to-use CMS for a small nonprofit. I've prototyped a website framework that's hosted
on Google Drive. So far it looks promising, but changes require being able to edit the html. We have a number of people who can create content in a word-processor-like environment but only couple including myself
who can cope with HTML/CSS/JQuery/AppsScript.
If I could concentrate on the overall framework and let the others update the content for
events, etc., that would be a huge win. Basically, I'd be very happy if they were able to edit the Google Doc and then manually reload the web page to see the result.
I realize there are many approaches for CMS, but for now, I'm interested in exploring a pure Google Docs/Google Drive solution.
I've settled on publishing the content docs and including the iframe embed code supplied by Google to implement the "MAGIC" from my original question, e.g
<iframe class="cmsframe" src="https://docs.google.com/document/d/1rhkuAB3IIu5Hq0tEtA4E_Qy_-sJMMnb33WBMlAEqlJU/pub?embedded=true"></iframe>
The class tag is added manually so I can control the iframe size with CSS.
You can get the raw html content of a google doc with a call to the drive API using urlFetch, here is how it works
var id = 'Doc-Very-Long-ID-Here';
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
// the variable doc is the HTML content that you can use
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
There is also a library by Romain Vialard available here it is called DocsListExtended and provides a whole bunch of nice extensions.
EDIT : Following your EDIT:
You can't use it just like that, to render an HTML content in a webapp use html service, example below with your complete code and working example:
function doGet() {
var id = '1el3DpTp1sukDjzlKXh8plf0Zj-qm0drI7KbytroVrNU';
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id, googleOAuth_('docs',url)).getContentText();
return HtmlService.createHtmlOutput(doc);
}
// the variable doc is the HTML content that you can use
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}