简体   繁体   中英

SPO Modern: How to inject and execute webpart programmatically, using js?

我只有 webpart 的 URL(例如 'https://sitename.com/sites/site-colection/ClientSideAssets/hereisguid/webpartname.js'),我需要通过 js 以编程方式注入和运行它,这可能吗?

It's not officially supported but You can use global variable (available on every modern page) _spComponentLoader. The problem is - it requires You to provide WebPartContext which You cannot simply get outside of SPFx.

If You want to do it in SPFx here is a sample code:

webPartId = hereisguid from Your url

        let component = await _spComponentLoader.loadComponentById(webPartId);
        let manifest = _spComponentLoader.tryGetManifestById(webPartId);
        let wpInstance = new component.default();
        context.manifest = manifest;
        //@ts-ignore
        context._domElement = document.getElementById("<id-of-element-you-want-wp-to-render-in>")
        await wpInstance._internalInitialize(context, {}, 1);
        wpInstance._properties = webPart.properties;

        await wpInstance.onInit();
        wpInstance.render();
        wpInstance._renderedOnce = true;

Again - I don't think it's supported so try it on Your own risk. Note this web part must be available at the site You are going to execute this script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM