Executing a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code:

cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) {
'use strict';

var exec = require('cordova/exec');

var sms = {};

function convertPhoneToArray(phone) {
    if (typeof phone === 'string' && phone.indexOf(',') !== -1) {
        phone = phone.split(',');
    }
    if (Object.prototype.toString.call(phone) !== '[object Array]') {
        phone = [phone];
    }
    return phone;
}


sms.send = function(phone, message, filename, options, success, failure) {
    // parsing phone numbers
    phone = convertPhoneToArray(phone);

    // parsing options
    var replaceLineBreaks = false;
    var androidIntent = '';
    if (typeof options === 'string') { // ensuring backward compatibility
        window.console.warn('[DEPRECATED] Passing a string as a third argument is deprecated. Please refer to the documentation to pass the right parameter: https://github.com/cordova-sms/cordova-sms-plugin.');
        androidIntent = options;
    }
    else if (typeof options === 'object') {
        replaceLineBreaks = options.replaceLineBreaks || false;
        if (options.android && typeof options.android === 'object') {
            androidIntent = options.android.intent;
        }
    }

    // fire
    exec(
        success,
        failure,
        'Sms',
        'send', [phone, message, filename, androidIntent, replaceLineBreaks]
    );
};

sms.hasPermission = function(success, failure) {
    // fire
    exec(
        success,
        failure,
        'Sms',
        'has_permission', []
    );
};

module.exports = sms;
});

Now, I am trying to access the sms.send(...) function in my Typescript code. I have attempted to import the file using various methods like :

import sms from '../../../plugins/cordova-sms-plugin/www/sms.js';

or

import * as Sms from '../../../plugins/cordova-sms-plugin/www/sms.js';

or

window['window']['sms']['send'](...)

However, none of these approaches seem to be working as Ionic cannot locate the send() function. Can anyone offer guidance on how to resolve this issue?

Answer №1

Your approach to calling the function is incorrect. You do not need to import a .js file in your .ts file. You have two options - either call directly using a global scope variable or create a .d.ts definition file for the plugin interface and import it into your .ts file. Once you've ensured that the plugin is installed correctly, follow these steps to call cordova-sms-plugin from your TS file:

Step-1. Refer to JS variable using window object by declaring it in your .ts file

declare var window: any;

Step-2. Call the function like this: window.sms.send

 let phone: string;
//Set the value of phone
let message: string;
//Set the value of message
let options  = {
            "replaceLineBreaks: false"
            //
        };
 //Call the function
 window.sms.send(phone,message,options,(result: any) => {
            console.log("Successfully Done...");
        }, (err: any) => {
            console.log("An error has occurred :" + err.code);
        })

I also found a sample project on GitHub for you to refer to for code examples:

https://github.com/abritopach/ionic-receiver-sms

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have encountered a problem with ejs-mate where I am experiencing an issue with the <%- layout("path") %> command. Even though the path is accurate, it is not functioning correctly

Error Message: Unable to locate file at 'D:\Web Projects\major\views\listings\layouts\boilerplate.ejs' I have made numerous attempts to resolve this issue, but unfortunately, I keep encountering the same error. I ha ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

Preventing page reload in Supabase with NextJS when the website loses focus and regains it

I am working with the structure in _app.js of my Next.js app. // _app.js // import ... import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs' import { SessionContextProvider } from '@supabase/auth-helpers-react' // ...

Discovering common elements in various arrays of objects

Details: record1 = [{"site": "The Blue Tiger", "zipcode": "E1 6QE"}, {"site": "Cafe Deluxe", "zipcode": "E6 5FD"}] record2 = [{"site": "Blue Tiger", "zi ...

I am having trouble getting the guide for setting up a NextJS app with Typescript to function properly

For some time now, I have been experimenting with integrating Typescript into my NextJS projects. Initially, I believed that getting started with Typescript would be the most challenging part, but it turns out that installing it is proving to be even more ...

Submitting data from a dropdown menu using Ajax in Struts 2: A step-by-step guide

I have a select tag with the s:select element inside a form. My goal is to send a post request to the specified action using Struts 2 json plugin. I do not have much knowledge in javascript or jquery. <s:form action="selectFileType" method="post" ...

Using Ajax, the script triggers calls upon detecting keyup events on various input fields, each

I'm encountering issues while attempting to solve this logic puzzle. The page contains multiple fields and the goal is to store the input values in the database when the user finishes typing. Here's the code snippet: var debounce = null; ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

I am experiencing some issues with my AngularJS JavaScript code. The root scope is updating correctly, but the other two scopes are not working as expected. Can

My attempt at writing AngularJS JavaScript code seems to be malfunctioning. While the root scope updates properly, the other two scopes FirstCtrl and SecondCtrl do not update as expected when the root scope is updated. I would like all three scopes to upd ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

Alternate. (individually)

Issue with Running Program I've been struggling to get my program to run correctly. The task at hand is to have the program display only one question at a time. But no matter what I try, clicking on all questions displays all the answers simultaneous ...

What is the best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ...

Experiencing difficulties retrieving HTTP response in Worklight versions 6.2 and 6.3

Error: WLNativeXHRPlugin$NativeXHRPostListener.onException 03-06 12:35:07.406: D/NONE(10503): Transfer failed, errors = {"invocationContext":null,"errorCode":"REQUEST_TIMEOUT","errorMsg":"Request timed out for http://192.168.85.1:10080/RestServiceCommunic ...

Turn off Chrome Autofill feature when placeholders are being used in forms

I am encountering difficulties with Google autofill for fields that have placeholders. Despite attempting various solutions provided at: Disabling Chrome Autofill, none of them seem to work as needed. The challenge is to create a form with different field ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

Utilizing Protractor, TypeScript, and Jasmine for Automated Testing

Just landed a new job at a company that uses protractor, jasmine, and Type Script for automation testing. While I have experience with selenium and Java, I'm unfamiliar with protractor. Can someone guide me on how to start protractor testing? Is there ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

Tips for sidestepping the need for casting the class type of an instance

Looking to develop a function that can accept an argument containing a service name and return an instance of that particular service, all while ensuring proper typing. Casting the instance seems necessary in order to achieve the desired result. To illust ...

Utilizing a JavaScript function to toggle the Bootstrap dropdown without the need for manual clicking

I've configured a Bootstrap dropdown in my site's mini cart that includes a lightbox effect to grey out the background content when the dropdown is activated. Here's the code snippet: $(".dropdown").on('show.bs.dropdown hide.bs.dropdow ...