How to retrieve the Query string value from web word instance

↘锁芯ラ 提交于 2020-01-16 08:44:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!