问题
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, ' '));
}
回答1:
What you should use instead?
You should use Office.js API that's defined here
https://docs.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
来源:https://stackoverflow.com/questions/58709035/how-to-retrieve-the-query-string-value-from-web-word-instance