【问题标题】:Sharepoint 2013 Hosted App execute javascript on all pages loadSharepoint 2013 托管应用程序在所有页面加载时执行 javascript
【发布时间】:2015-10-27 14:51:12
【问题描述】:

我想知道是否有可能拥有一个 SP 2013 托管应用程序,该应用程序注入一段在每次页面加载时执行的 Javascript。

为了简单起见,假设我想创建一个应用程序,在 SP 站点的每个页面加载时都显示一个 alert('Hello world!');

我不想拥有任何人都可以通过从 SP 商店中挑选来添加的、纯粹而简单的远程 Web 托管应用程序。

这可能吗?

谢谢!

【问题讨论】:

    标签: javascript sharepoint sharepoint-2013 hosted-app sharepoint-jsom


    【解决方案1】:

    您可以按照@AlexCode 的建议使用自定义操作脚本链接注入 javascript,但该应用需要web - full control 权限。我不记得我在研究插件开发时从哪里改编了这段代码。此外,这仅适用于 POC,您可能应该在实际环境中使用它之前使其更加健壮。

    App.js 内容

    (function(undefined) {
        "use strict";
        var actions, web, context, hostContext, actionDescription;
        console.log('running function');
        // getQueryStringParameter: method to retrieve query string parameter values
        var getQueryStringParameter = function(param) {
    
                var params = document.URL.split('?')[1].split('&');
                var length = params.length;
                for (var i = 0; i < length; i = i + 1) {
                    var singleParam = params[i].split('=');
                    if (singleParam[0] == param) {
                        return singleParam[1];
                    }
                }
            };
    
        // inject: method to return as a string the js that will be ran by the custom action
        var inject = function() {
                debugger;
                var scriptToRun;
    
                scriptToRun += '(function (){' +
                        'var elem = document.getElementsByTagName("head")[0];' +                    
                        'var script = document.createElement("script");' +
                        'script.appendChild(document.createTextNode(alert("hello world")));' +                  
                        'elem.appendChild(script);' +
                    '}());';
    
                return scriptToRun;
            };
    
        var success = function() {
            alert('Done');
        }
    
        var fail = function() {
            alert('Failed');
        }
    
        // unprovision: removes the custom action and the JavaScript file
        var unprovision = function() {
                context = SP.ClientContext.get_current();
                hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter('SPHostUrl')));
                // load the custom actions from the host web
                actions = hostContext.get_web().get_userCustomActions();
                context.load(actions);
                web = hostContext.get_web();
                context.load(web);
                context.executeQueryAsync(unprovisionEx, fail);
            };
    
        // unprovisionEx: method to remove the custom action
        var unprovisionEx = function() {
                var enumerator = actions.getEnumerator();
                var removeThese = [];
                // find the custom action
                while (enumerator.moveNext()) {
                    var action = enumerator.get_current();
                    if (action.get_description() == actionDescription && action.get_location() == 'ScriptLink') {
                        // add it to a temporary array (we cannot modify an enumerator while enumerating)
                        removeThese.push(action);
                    }
                }
                // do the actual removal of the custom action
                var length = removeThese.length;
                for (var i = 0; i < length; i++) {
                    removeThese[i].deleteObject();
                    delete removeThese[i];
                }
    
                context.executeQueryAsync(success, fail);
            };
    
    
        // provisionScriptLink: method that adds the custom action
        var provisionScriptLink = function() {
                var enumerator = actions.getEnumerator();
                var removeThese = [];
                // check if the custom action already exists, if it does then remove it before adding the new one
                while (enumerator.moveNext()) {
                    var action = enumerator.get_current();
                    if (action.get_description() == actionDescription && action.get_location() == 'ScriptLink') {
                        removeThese.push(action);
                    }
                }
    
                var length = removeThese.length;
                for (var i = 0; i < length; i++) {
                    removeThese[i].deleteObject();
                    delete removeThese[i];
                }
    
                // create the custom action
                var newAction = actions.add();
                // the 'description' is what we'll use to uniquely identify our custom action
                newAction.set_description(actionDescription);
                newAction.set_location('ScriptLink');
                newAction.set_scriptBlock(inject());
    
                newAction.update();
                context.executeQueryAsync(success, fail);
            };
    
        // provision: starts with uploading the JavaScript file to the host we, once done it will continue with the provisionScriptLink() method
        var provision = function() {
                context = SP.ClientContext.get_current();
                hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter('SPHostUrl')));
                // load the custom actions from the host web
                actions = hostContext.get_web().get_userCustomActions();
                context.load(actions);
                web = hostContext.get_web();
                context.load(web);
    
                context.executeQueryAsync(provisionScriptLink, fail);
            };
    
    
        document.getElementById("add").onclick = provision;
    
    }());
    

    Default.apsx 内容

    <%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
    
    <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
    
    <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    
    <%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    
        <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
        <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    
        <!-- Add your CSS styles to the following file -->
        <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
    
    </asp:Content>
    
    <%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
        Page Title
    </asp:Content>
    
    <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    
        <div>
           <button type="button" value="add" name="add" id="add">Add</button>
        </div>
    
    </asp:Content>
    
    <asp:Content ContentPlaceHolderID="PlaceHolderUtilityContent" runat="server">
        <!-- Add your JavaScript to the following file -->
        <script type="text/javascript" src="../Scripts/App.js"></script>
    </asp:Content>
    

    【讨论】:

      【解决方案2】:

      您可以通过 javascript 从应用站点向主机站点提供自定义母版页。无论如何,主机站点必须使用新的母版页。

      您可以查看this article了解更多信息

      【讨论】:

      • 如果我理解得很好,那不是一个选择。作为 SP 托管应用程序提供商,我无法控制主机 Web,我不能强迫任何人这样做。我相信方法是通过 CustomAction ScriptLink 但我不确定如何。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2013-05-31
      • 2022-08-22
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      相关资源
      最近更新 更多