Access items inside Webpack bundle in browser console - javascript

I am using Typescript with Webpack (debug build using source maps). I can access Static class files in the sources tab normally. However, the class name itself is undefined at the global scope.
class SomeStaticClass {
public static doSomething() {
console.log("I just did something!");
}
}
I would like to access / call
SomeStaticClass.doSomething()
from console in the browser (say Google Chrome Inspector Tools).

Assuming that you want to get all files, you can do something like this:
window.SomeStaticClass = require('./path-to-file-with-class').default;
Inspired by workwise's answer

you can call the static method by
console.log(SomeStaticClass.doSomething())
I managed to make it work refer this url

I managed a workaround like the following. In the main exports.tsx (assuming this is the top level export):
import { StaticClassToBeExposed } from '...SomeFile';
if(type of window !== undefined) {
window.StaticClassToBeExposed = StaticClassToBeExposed;
}

Related

Vaadin 14 Springboot javascript does not work

I'm trying to develop my first Vaadin 14 application, I'm also using Spring boot framework for it.
I've created a javascript file, I put it into the folder frontend/src with the name of teams.js and I'm trying to import it with #JsModule("src/teams.js"). My root view class looks like this:
#Route("")
#PageTitle("Teams organization store init")
#Slf4j
#JsModule("src/teams.js")
#Tag("TeamsEntry")
public class TeamsEntryView extends VerticalLayout implements BeforeEnterObserver {
public TeamsEntryView() {
initTeams();
}
private void initTeams() {
var ui = UI.getCurrent();
var page = ui.getPage();
log.info("Teams initialization...");
page.executeJs(getTeamsConfig()).toCompletableFuture().whenComplete(((jsonValue, throwable) ->
log.info("Teams initialization completed: {} with throwable {}", jsonValue.toJson(), throwable.getMessage())
));
}
private String getTeamsConfig() {
return """
console.log('ss');
window.initTeams();
console.log('xx');
return true;
""";
}
...
My js file looks like this:
window = {
initTeams: function () {
console.log('initTeams...');
}
}
In this case, I see "ss" in the browser's console, but nothing more.
If I remove the window.initTeams(); line I get "ss" and "xx" as well.
If I declare a simple function in the js file and call it without the "window" class I get similar results.
If I use #Javascript or page.addJavascript("src/teams.js") I get this error when the page loads: "> unexpected character"
If I try to call join() or get() on the completable future the browser freeze.
If I use #Javascript("frontend://src/teams.js") I get some CORS error like if it is trying to download something from the "frontend" host.
I've tried to put the #JsModule on a component instead of my view.. it does not work.
I've tried to put my js file to the root, and to the resources folder.
I could not find any other solution to import and use my js file into vaadin14 with spring boot.
Also, I'm not sure why the browser freeze if I call "join()" on completable future, and also the on the result of it sentToBrowser returns false even if I see the console logs in the browsers log...
Can somebody explain to me how should I do the javascript import, why my current code does not work, and why the "join()" freezes the browser, please?
Thank you in advance!
#Edit
I have also tried with this annotation #JavaScript("./src/teams.js") and a js like this:
function initTeams () {
console.log('initTeams...');
console.log("Teams initialized!")
}
#Edit
Okay so finally I got it working.
The js file has to be under root/src/main/webapp/src folder.
Nor #JavaScript and nor the #JsModule worked for me, so I had to import my js file as:
var ui = UI.getCurrent();
var page = ui.getPage();
page.addJavaScript("src/teams.js");
Then I can call it like window.initTeams() or like initTeams() and both works fine. Altough the completable future below still never executes, and isSentToBrowser() always returns false.
page.executeJs(getTeamsConfig()).toCompletableFuture().whenComplete(((jsonValue, throwable) ->
log.info("Teams initialization completed: {} with throwable {}", jsonValue.toJson(), throwable.getMessage())
));
I must mention if I start the path with '.' like page.addJavaScript(".src/teams.js"); then it does not find the file.
Does anybody have an answer, why the completable future never executes?
The problem is that the following code redefines the window object:
window = {
initTeams: function () {
console.log('initTeams...');
}
}
Did you meant to add a function to the window object? Like so:
window.initTeams = function () {
console.log('initTeams...');
};
If you want to keep code visually similar to yours:
window = {
...window,
{
initTeams: function() {
console.log('initTeams...');
}
}
}
Other options:
window['initTeams'] = function() {...}
Object.assign(window, {initTeams: function() {...}})
Object.defineProperty(window, 'initTeams', {value: function() {console.log('foo')}});
Gotta love JavaScript...
Also, for more knowledge, the code mentioned in your #Edit section could not be called. Calling initTeams() is equivalent to window.initTeams(). The function must exist in the window object. This is why, for example, you see some custom elements defined like customElements.define(...) and window.customElements.define(...).

Accessing External Javascript Lib in React Store

I have a React app which the components are controlled by a Store.ts file.
I followed some steps in other threads here on Stack Overflow. I've already included the script tag in my index.html like this:
<script type="text/javascript" src="https://stc.sandbox.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js"></script>
Then, as stated in here, in my Store, before using one of the functions, I declared the library as part of window as follow:
declare global {
interface Window { PagSeguroDirectPayment: any; }
}
window.PagSeguroDirectPayment = window.PagSeguroDirectPayment || {};
window.PagSeguroDirectPayment.setSessionId('620f99e348c24f07877c927b353e49d3');
But when I run the app I get the error window.PagSeguroDirectPayment.setSessionId is not a function. And when I call the function directly in the index.html it seems to work.
Am I declaring it in the wrong place or in the wrong way?
I appreciate any help. Thanks in advance
The solution is to use globally declared elements with the window prefix.
E.g: window.PagSeguroDirectPayment
Note:
But without instructions like:
window.PagSeguroDirectPayment = window.PagSeguroDirectPayment || {}
because window.PagSeguroDirectPayment features are required.
Maybe that can help.

How do you manage namespace in Meteor?

So here is my problem :
Currently, I have a dozen of functions related to WEBRTC within a template js file. My objective is to have those functions in a separate file, called webRTCWrapper.js for example, and to call those functions in my template without using global variable.
I think I must use namespaces, am I correct ?
If so, how do you use them ?
EDIT : For anyone interested, this is exactly what I was looking for :
http://themeteorchef.com/snippets/using-the-module-pattern-with-meteor/
Make a directory called packages/ parallel to your .meteor/ directory. You can create a package that exports a single object/function. On the command line, use meteor create --package <yourpackagename> and meteor add <yourpackagename> You can edit the js file to add a namespace.
MyNamespace = {};
MyNamespace.myFunction = function () { };
Then, in the package.js, simply export that namespace.
api.export('MyNamespace');
You can use a common pattern of having a global object and your functions inside that object.
Greetings = {
hello: function(name) { return "Hello "+name+" how are you?"; }
}
And then you can call it inside the template helpers :
Template.GreetingsTemplate.helpers({
sayHello: function() { return Greetings.hello('Maxence'); }
})
Take note of the loading order of files in Meteor, anything inside the lib folders is loaded first. If you run into problems where "Greetings" object is not defined, then its because that file was not loaded already.
Edit:
You can reuse the same pattern for adding more functions in different files (you could use App = App || {} but it will throw error in Chrome for example).
App = (typeof App === 'undefined')? {} : App;
App.someFunction = function(){};
or even, if you use underscore.js:
App = (typeof App === 'undefined')? {} : App;
_.extend(App, {
someFunction: function(){}
});
Since now the regular way to use the code from another file was going through a global (server and client). As Joao suggested you can make your own global App variable where you will store or more generically a global MODULE one (basically the same solution as Joao but with explanation).
But with with the arrival of ES2015 support, we will very soon be able to have an official pattern to achieve this. However as the 1.2 does not supports yet the import/export syntax:
Note, The ES2015 module syntax (import/export) is not supported yet in Meteor 1.2.
If you want to start using those features earlier, I would recommend using this package which is an temporary solution to fill the current import/export gap, the meteor team development are currently looking for an elegant solution to support this.

TypeScript file not loaded or something

I get an error in my console when I try to create a type script file from a partial view (MVC .NET) which is loaded by a rest call and appended to a div element.
I get: Uncaught ReferenceError: xyz is not defined.
in my partial view i have below code:
<script type="text/javascript">
$(document).ready(function () {
var model = #Html.GetJson(Model.x);
var view = new xyz.ExceptionView();
view.init();
});
</script>
Edit: I added "#section scripts {}" around my script tag and then i get nothing in my console and no execution or logging from implementation
And I forgot to mention that my TypeScript file is not implementing anything. But here it is.
Is this not a correct way of using typescript?
module xyz {
export class ExceptionView {
constructor() {
debugger;
}
public init = (model: any): void => {
debugger;
}
}
}
As you can't include or reference TypeScript directly in your HTML, I assume you have a script tag that includes the compiled JavaScript? Does the JavaScript emitted from the TypeScript compilation look right? Are you able to step through the final JavaScript code in the browser Web Developer Tools and see where the breakdown is occurring?

Using a Javascript Function from Typescript

I am trying to build a nice windows phone application with an HTML front end. I want to use TYPESCRIPT to do my processing onto my html page. There is one javascript function which is crucial for my application to work - window.external.notify
This method isn't created till runtime I assume, so I build a javascript wrapper function to determine if it exists when it is called.
if (window.external.notify != undefined)
window.external.notify(msg);
The issue is I need to get my Typescript files to see this function.
I am using Visual Studio 2012 and I have seen the post - How to use an exported function within the local module
The issue is when I just include my javascript file with the function I want to use I get the error TS2095.
error TS2095: Build: Could not find symbol
Any ideas or help or possible SDKs to circumvent this issue?
//notif.js
let notify = function(message) {
alert(message);
}
//test.ts
declare function notify(message: string): any;
if(notify != undefined)
notify("your message");
Make sure notif.js is loaded first.
You need to tell typescript that this function exists on window.external in order to use it. So :
interface External{
notify: Function;
}
if (window.external.notify != undefined)
window.external.notify("your message");

Categories

Resources