Javascript 将工具栏按钮添加到嵌入式查看器

Javascript 将工具栏按钮添加到嵌入式查看器,javascript,autodesk-forge,autodesk-viewer,Javascript,Autodesk Forge,Autodesk Viewer,我一直在学习如何使用所描述的公共共享文件自定义查看器的教程。我想在查看器中添加一个按钮,但是我不断收到错误Uncaught(in promise)Extension not found:HandleSelectionExtension。是否已注册(1)?。以下是我在html页面中包含的js函数代码: var viewer; displayViewer(); //CODE FOR CUSTOMER VIEWER function displayViewer(){ // assemblynam

我一直在学习如何使用所描述的公共共享文件自定义查看器的教程。我想在查看器中添加一个按钮,但是我不断收到错误
Uncaught(in promise)Extension not found:HandleSelectionExtension。是否已注册(1)?
。以下是我在html页面中包含的js函数代码:

var viewer;
displayViewer();
//CODE FOR CUSTOMER VIEWER
function displayViewer(){
  //  assemblyname = '';
var embedURLfromA360 = "https://afasystemsinc2.autodesk360.com/shares/public/SH56a43QTfd62c1cd96838ebd0c0ce1c251d?mode=embed";


function getURN(onURNCallback) {
    $.get({
        url: embedURLfromA360.replace('public', 'metadata').replace('mode=embed', ''),
        dataType: 'json',
        success: function (metadata) {
            if (onURNCallback) {
                onURNCallback(metadata.success.body.viewing.views.viewableUrn);
            }
        }
    })
}

function getForgeToken(onTokenCallback) {
    $.post({
        url: embedURLfromA360.replace('public', 'sign').replace('mode=embed', 'oauth2=true'),
        data: '{}',
        success: function (oauth) {
            if (onTokenCallback)
                onTokenCallback(oauth.accessToken, oauth.validitySeconds);
        }
    });
}

getURN(function (urn) {
    var options = {
        env: 'AutodeskProduction',
        getAccessToken: getForgeToken
    };
    var documentId = 'urn:' + urn;
    Autodesk.Viewing.Initializer(options, function onInitialized() {
        Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
    });
});

// used by viewer.addEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, onToolbarCreated)

const onToolbarCreated = (e) => {
    const settingsTools = viewer.toolbar.getControl('settingsTools')
    /*
    settingsTools.removeControl('toolbar-modelStructureTool') 
    settingsTools.removeControl('toolbar-propertiesTool')            
    settingsTools.removeControl('toolbar-settingsTool')          
    settingsTools.removeControl('toolbar-fullscreenTool')           
*/
    viewer.removeEventListener(
        Autodesk.Viewing.TOOLBAR_CREATED_EVENT,
        onToolbarCreated)  
} 

/**
 * Autodesk.Viewing.Document.load() success callback.
 * Proceeds with model initialization.
 */
function onDocumentLoadSuccess(doc) {

    // A document contains references to 3D and 2D viewables.
    var viewables = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
        'type': 'geometry'
    }, true);
    if (viewables.length === 0) {
        console.error('Document contains no viewables.');
        return;
    }

    // Choose any of the avialble viewables
    var initialViewable = viewables[0];
    var svfUrl = doc.getViewablePath(initialViewable);
    var modelOptions = {
        sharedPropertyDbPath: doc.getPropertyDbPath()
    };

   // var viewerDiv = document.getElementById('MyViewerDiv');
 //viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);

 viewer = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv'),{extensions:['HandleSelectionExtension', 'ModelSummaryExtension']});

    // Our customization of the Viewer: we are removing some of the toolbar buttons
    viewer.addEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, onToolbarCreated)
    viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
}

/**
 * Autodesk.Viewing.Document.load() failuire callback.
 */
function onDocumentLoadFailure(viewerErrorCode) {}

/**
 * viewer.loadModel() success callback.
 * Invoked after the model's SVF has been initially loaded.
 * It may trigger before any geometry has been downloaded and displayed on-screen.
 */
function onLoadModelSuccess(model) {}

/**
 * viewer.loadModel() failure callback.
 * Invoked when there's an error fetching the SVF file.
 */
function onLoadModelError(viewerErrorCode) {}
}
function view(){
    console.log(viewer);
}

function destroyViewer(){
    console.log(viewer);
    console.log(viewer.contextMenu);
    viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
console.log(viewer);
}

var ext = '';
var dim = '';
var assemblyname = '';

function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
//dim = ext[0];
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
    isolateSelected();
}
}


//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
    isolateSelectedPart();
}
}

function isolateSelected(){
    console.log(dim);
    console.log(viewer);
   /* if (viewer == null){
        getItem();
    }*/
    viewer.search(dim, function(dbIds) {
   // viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
        console.log(dbIds.length);
       if (dbIds.length == 0){
        dim = ext[0] + ':2';
       // isolateSelected();
     }
        getSubset(dbIds, 'label', dim, function(dbIds) {
       // getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
       // getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
            //getSubset(dbIds, property.name, property.value, function(dbIds){
            var it = viewer.model.getData().instanceTree;
            //console.log(it);
           for (i = 0; i<dbIds.length; i++){
               var namepart = it.getNodeName(dbIds[i]);
               if (namepart !== undefined){
            console.log(dbIds);
            console.log(namepart);}}
          /*  for (i = 121; i<381;i++){
                var dbId = i;
            var it = NOP_VIEWER.model.getData().instanceTree;
            var name = it.getNodeName(dbId);
            console.log(name);}*/
           // viewer.setBackgroundColor(255,0,0,255,0,0);
         //  viewer.setSelectionColor(new THREE.Color(1,1,1));
        // viewer.setSelectionColor(new THREE.Color(0xFFAB33));
        viewer.setSelectionColor(new THREE.Color(0xFFC000));
          //  viewer.setBackgroundOpacity(1.0);
            viewer.isolate(dbIds)
           viewer.select(dbIds);
            viewer.utilities.fitToView();
            $(window).scrollTop(300);
        })
    }, function(error) {})
}

function isolateSelectedPart(){
    console.log(namewithoutextension);
    if (viewer == null){
        getItem();
    }
    viewer.search(namewithoutextension, function(dbIds) {
   // viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
        console.log(dbIds.length);
        if (dbIds.length == 0){
            getItem();
        }
        getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
       // getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
       // getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
            //getSubset(dbIds, property.name, property.value, function(dbIds){
            var it = viewer.model.getData().instanceTree;
            //console.log(it);
           for (i = 0; i<dbIds.length; i++){
               var namepart = it.getNodeName(dbIds[i]);
               if (namepart !== undefined){
            console.log(dbIds);
            console.log(namepart);}}
          /*  for (i = 121; i<381;i++){
                var dbId = i;
            var it = NOP_VIEWER.model.getData().instanceTree;
            var name = it.getNodeName(dbId);
            console.log(name);}*/
            viewer.setSelectionColor(new THREE.Color(0xFFC000));
           // viewer.setBackgroundOpacity(1.0);
            viewer.isolate(dbIds)
           viewer.select(dbIds);
            viewer.utilities.fitToView();
            $(window).scrollTop(300);
        })
    }, function(error) {})
}

//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
    console.log("getSubset, dbIds.length before = " + dbIds.length)
    viewer.model.getBulkProperties(dbIds, {
        propFilter: [name],
        ignoreHidden: true
    }, function(data) {
        var newDbIds = []
        for (var key in data) {
            var item = data[key]
           // console.log(item.properties);
            if (item.properties[0].displayValue === value) {
                newDbIds.push(item.dbId)
            }
        }

        console.log("getSubset, dbIds.length after = " + newDbIds.length)

        callback(newDbIds)

    }, function(error) {})
}

class HandleSelectionExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this._group = null;
        this._button = null;
    }

    load() {
        console.log('HandleSelectionExtension has been loaded');
        return true;
    }

    unload() {
        // Clean our UI elements if we added any
        if (this._group) {
            this._group.removeControl(this._button);
            if (this._group.getNumberOfControls() === 0) {
                this.viewer.toolbar.removeControl(this._group);
            }
        }
        console.log('HandleSelectionExtension has been unloaded');
        return true;
    }

    onToolbarCreated() {
        // Create a new toolbar group if it doesn't exist
        this._group = this.viewer.toolbar.getControl('allMyAwesomeExtensionsToolbar');
        if (!this._group) {
            this._group = new Autodesk.Viewing.UI.ControlGroup('allMyAwesomeExtensionsToolbar');
            this.viewer.toolbar.addControl(this._group);
        }

        // Add a new button to the toolbar group
        this._button = new Autodesk.Viewing.UI.Button('handleSelectionExtensionButton');
        this._button.onClick = (ev) => {
            const selection = this.viewer.getSelection();
this.viewer.clearSelection();
// Anything selected?
if (selection.length > 0) {
    let isolated = [];
    // Iterate through the list of selected dbIds
    selection.forEach((dbId) => {
        // Get properties of each dbId
        this.viewer.getProperties(dbId, (props) => {
            // Output properties to console
            console.log(props);
            console.log(props.name);
            // Ask if want to isolate
          //  if (confirm(`Isolate ${props.name} (${props.externalId})?`)) {
                isolated.push(dbId);
                this.viewer.isolate(isolated);
                //window.open('mailto:test@example.com?subject=subject&body='+props.name);
            //}
        });
    });
} else {
    // If nothing selected, restore
    this.viewer.isolate(0);
}
        };
        this._button.setToolTip('Isolate Part');
        this._button.addClass('handleSelectionExtensionIcon');
        this._group.addControl(this._button);
    }
}

Autodesk.Viewing.theExtensionManager.registerExtension('HandleSelectionExtension', HandleSelectionExtension);

//CODE FOR BUTTON TO ORDER A SPARE PART

class ModelSummaryExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this._group = null;
        this._button = null;
    }

    load() {
        console.log('ModelSummaryExtension has been loaded');
        return true;
    }

    unload() {
        // Clean our UI elements if we added any
        if (this._group) {
            this._group.removeControl(this._button);
            if (this._group.getNumberOfControls() === 0) {
                this.viewer.toolbar.removeControl(this._group);
            }
        }
        console.log('ModelSummaryExtension has been unloaded');
        return true;
    }

    onToolbarCreated() {
        // Create a new toolbar group if it doesn't exist
        this._group = this.viewer.toolbar.getControl('allMyAwesomeExtensionsToolbar');
        if (!this._group) {
            this._group = new Autodesk.Viewing.UI.ControlGroup('allMyAwesomeExtensionsToolbar');
            this.viewer.toolbar.addControl(this._group);
        }

        // Add a new button to the toolbar group
        this._button = new Autodesk.Viewing.UI.Button('ModelSummaryExtensionButton');
        this._button.onClick = (ev) => {
            // Execute an action here
            // Get current selection
const selection = this.viewer.getSelection();
this.viewer.clearSelection();
// Anything selected?
if (selection.length > 0) {
    let isolated = [];
    // Iterate through the list of selected dbIds
    selection.forEach((dbId) => {
        // Get properties of each dbId
        this.viewer.getProperties(dbId, (props) => {
            // Output properties to console
            console.log(props);
            // Ask if want to isolate
            if (confirm(`Would you like to order a spare of ${props.name} ?`)) {
                isolated.push(dbId);
                this.viewer.isolate(isolated);
                window.open('mailto:test@example.com?subject=subject&body='+props.name);
            }
        });
    });
} else {
    // If nothing selected, restore
    this.viewer.isolate(0);
}
        };
        this._button.setToolTip('Order this Part');
        this._button.addClass('modelSummaryExtensionIcon');
        this._group.addControl(this._button);
    }
}

Autodesk.Viewing.theExtensionManager.registerExtension('ModelSummaryExtension', ModelSummaryExtension);
var查看器;
displayViewer();
//客户查看器代码
函数displayViewer(){
//assemblyname='';
变量embedURLfromA360=”https://afasystemsinc2.autodesk360.com/shares/public/SH56a43QTfd62c1cd96838ebd0c0ce1c251d?mode=embed";
函数getURN(onURNCallback){
美元({
url:embedURLfromA360.replace('public','metadata').replace('mode=embed',''),
数据类型:“json”,
成功:函数(元数据){
if(onURNCallback){
onURNCallback(metadata.success.body.viewing.views.viewableUrn);
}
}
})
}
函数getForgeToken(onTokenCallback){
美元邮政({
url:embedURLfromA360.replace('public','sign').replace('mode=embed','oauth2=true'),
数据:“{}”,
成功:功能(oauth){
如果(回调)
onTokenCallback(oauth.accessToken,oauth.validitySeconds);
}
});
}
getURN(函数(urn){
变量选项={
环境:“AutodeskProduction”,
getAccessToken:getForgeToken
};
var documentId='urn:'+urn;
Autodesk.Viewing.Initializer(选项,函数初始化(){
Autodesk.Viewing.Document.load(documentId、onDocumentLoadSuccess、onDocumentLoadFailure);
});
});
//由viewer.addEventListener使用(Autodesk.Viewing.TOOLBAR_已创建_事件,OnToolBar已创建)
const onToolbarCreated=(e)=>{
const settingsTools=viewer.toolbar.getControl('settingsTools')
/*
settingsTools.removeControl('toolbar-modelStructureTool')
settingsTools.removeControl('toolbar-propertiesTool')的设置
settingsTools.removeControl('toolbar-settingsTools')
settingsTools.removeControl('toolbar-fullscreenTool')
*/
viewer.removeEventListener(
Autodesk.Viewing.TOOLBAR\u已创建\u事件,
ONTOOLBAR(已创建)
} 
/**
*Autodesk.Viewing.Document.load()成功回调。
*继续进行模型初始化。
*/
函数onDocumentLoadSuccess(doc){
//文档包含对三维和二维视图的引用。
var viewables=Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(){
“类型”:“几何体”
},对);
如果(viewables.length==0){
console.error('文档不包含任何视图');
返回;
}
//选择任意一个Available视图
var initialViewable=viewables[0];
var svfUrl=doc.getViewablePath(initialViewable);
var模型选项={
sharedPropertyDbPath:doc.getPropertyDbPath()
};
//var viewerDiv=document.getElementById('MyViewerDiv');
//查看器=新的Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
viewer=new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('MyViewerDiv'),{extensions:['HandleSelectionExtension','ModelSummaryExtension']});
//我们对查看器的定制:我们正在删除一些工具栏按钮
viewer.addEventListener(Autodesk.Viewing.TOOLBAR_已创建_事件,OnToolBar已创建)
start(svfUrl、modelpoptions、onLoadModelSuccess、onLoadModelError);
}
/**
*Autodesk.Viewing.Document.load()失败回拨。
*/
函数onDocumentLoadFailure(viewerErrorCode){}
/**
*loadModel()成功回调。
*最初加载模型的SVF后调用。
*它可能会在任何几何体下载并显示在屏幕上之前触发。
*/
函数onLoadModelSuccess(model){}
/**
*viewer.loadModel()失败回调。
*在获取SVF文件时出错时调用。
*/
函数onLoadModelError(viewerErrorCode){}
}
函数视图(){
console.log(查看器);
}
函数developer(){
console.log(查看器);
console.log(viewer.contextMenu);
viewer.finish();
查看器=空;
Autodesk.view.shutdown();
console.log(查看器);
}
var-ext='';
var dim='';
var assemblyname='';
函数getAssemblyName(){
assemblyname=sessionStorage.getItem(“assemblyname”);
//var ext=partname.substr(partname.lastIndexOf('.');
ext=assemblyname.split('.');
尺寸=外部[0]+':1';
//dim=ext[0];
console.log(assemblyname);
控制台日志(dim);
如果(变暗!=''){
isolateSelected();
}
}
//函数从_MachineParts.php获取零件名称
var partname='';
var扩展=“”;
变量名称WithoutExtension='';
函数getPartName(){
partname=sessionStorage.getItem(“partname”);
//var ext=partname.substr(partname.lastIndexOf('.');
扩展名=partname.split('.');
namewithoutextension=扩展名[0]+':1
console.log(partname);
console.log(名称不带扩展名);
如果(名称不带扩展!=''){
isolateSelectedPart();
}
}
函数isolateSelected(){
控制台日志(dim);
console.log(查看器);
/*如果(查看器==null){
getItem();
}*/
viewer.search(dim、函数(dbIds){
//查看器.search(“+”M-109408折叠犁:2“+”,函数(dbIds){
log(dbIds.length);
if(dbIds.length==0){
尺寸=外部[0]+':2';
//isolateSelected();
}
getSubset(dbIds,'标签',dim,函数(dbIds){
//getSubset(dbIds,'标签','M-109408折叠犁:2',函数(dbIds){
//getSubset(dbIds,property.name,'M-54439 POST-tube:1',函数(dbIds){
//getSubset(dbIds、property.name、property.value、函数(dbIds){
var it=viewer.model.getData().instanceTree;
//console.log(it);
对于(i=0;i{
//在这里执行操作
//获取当前选择
const selection=this.viewer.getSelection();
this.viewer.clearSelection();
//选择了什么?
如果(selection.length>0){
设孤立=[];
//伊特
function onDocumentLoadSuccess(doc) {

  // A document contains references to 3D and 2D viewables.
  var viewables = doc.getRoot().search({
    'type': 'geometry'
  });
  if (viewables.length === 0) {
    console.error('Document contains no viewables.');
    return;
  } 

  // Choose any of the avialble viewables
  var initialViewable = viewables[0];
  var svfUrl = doc.getViewablePath(initialViewable);
  var modelOptions = {
    //sharedPropertyDbPath: doc.getPropertyDbPath()
  };

  viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('MyViewerDiv'),{extensions:['HandleSelectionExtension', 'ModelSummaryExtension']});

  // Our customization of the Viewer: we are removing some of the toolbar buttons
  viewer.addEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, onToolbarCreated)
  viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);
}
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css" type="text/css">
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.js"></script>