简体   繁体   中英

Function works when I put it in an onclick but doesn't work when I try to use in on page-load (JavaScript)

I am building a Microsoft VSTS extension using HTML JavaScript .

I need to access this function VSS.getWebContext() which gives you all information of the project page where you are currently running your extension.

let webContext = VSS.getWebContext();
let projectName = webContext.project.name + "_kpi_test"

# prints out fine
console.log('projname', projectName);

When I put this into an onclick function of a button , it works fine and prints the information that I need.

But when I just use

    $(window).ready(function(){
        // your code
    }); 

and

    $(document).ready(function(){
        // your code
    }); 

and

window.onload = codeAddress; //my function here

to use the VSS.getWebContext() to retrieve the information when the page loads, it keeps giving me that VSS.getWebContext() is undefined .

If it works on onClick but not on page-load, what could be the problem?

I am not sure what exactly VSS needs, but since it is working in onClick it is probably just that the page has not actually completely loaded yet in your document and window ready calls.

You could try:

$(window).bind("load", function() {
   // code here
});

There is an VSS.init and VSS.ready function, see use the SDK from vss-web-extension-sdk GitHub for more information.

In Angular & TypeScript:

  // VARIABLES VSS
  extensionInitializationOptions: IExtensionInitializationOptions = { applyTheme: false, usePlatformScripts: false, usePlatformStyles: false };

  async ngOnInit(): Promise<void> {
    if (environment.production) {
      // VSS INIT
      VSS.init(this.extensionInitializationOptions);

      // VSS READY
      VSS.ready(async () => {
        await this.init();
      });
    } else await this.init();
  }

environment.production for local debugging.

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