Removing external JS files when navigating to another page in VUEJS can be achieved by unloading the

I currently have a JavaScript component within the home component that utilizes an external script. My goal is to remove the external script when navigating to another page, without refreshing the page.

<script>
  function initFreshChat() {
    window.fcWidget.init({
      token: "***",
      host: "https://wchat.freshchat.com"
    });
  }
  function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);
</script>

The link to the external script:

This setup allows me to maintain the Freshchat window on one specific page. While I can achieve this with conditions, it requires a page refresh. As the pages do not refresh, I am seeking a solution to dynamically remove the external script when navigating to other pages and reinstate it upon returning to this particular page.

Answer №1

One way to handle the script is by encapsulating it within a Vue component life cycle,

  • render
  • remove
  • refresh

as needed.

Here's where I came across this code snippet on Codepen https://codepen.io/akccakcctw/pen/LBKQZE

Vue.component("fc-button", {
template: "#fcButton",
props: {
 fc: {
   type: Object,
   default: {},
 }
 
},
methods: {
 openWidget: function() {
   document.getElementById("fc_frame").style.visibility = "visible";
   window.fcWidget.open();
 }
}
});

const vm = new Vue({
el: "#app",
data: function() {
 return {
   fc: {
     isInit: false,
   },
 };
},
mounted: function() {
 var self = this;
 window.fcSettings = {
   token: "8d3a4a04-5562-4f59-8f66-f84a269897a1",
   host: "https://wchat.freshchat.com",
   config: {
     cssNames: {
       widget: "custom_fc_frame",
       open: "custom_fc_open",
       expanded: "custom_fc_expanded"
     },
     headerProperty: {
       hideChatButton: true
     }
   },
   onInit: function() {
     
     window.fcWidget.on("widget:loaded", function() {
       self.fc.isInit = true;
       window.fcWidget.on("unreadCount:notify", function(resp) {
         console.log(resp);
         test = resp;
         if (resp.count > 0) {
           // document.getElementById('notify').classList.add('h-btn-notify');
           document.getElementById("notify").style.visibility = "visible";
         } else if (resp.count == 0) {
           // document.getElementById('notify').classList.remove('h-btn-notify');
           document.getElementById("notify").style.visibility = "hidden";
         }
       });
       window.fcWidget.on("widget:closed", function() {
         document.getElementById("fc_frame").style.visibility = "hidden";
         document.getElementById("open_fc_widget").style.visibility =
           "visible";
       });
       window.fcWidget.on("widget:opened", function(resp) {
         document.getElementById("open_fc_widget").style.visibility =
           "hidden";
       });
     });
   }
 };
}
});

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

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

What is the best way to use Rails active storage and VueJS to directly upload files to S3?

I've encountered a challenge in uploading a file to s3 using direct upload s3. My current setup is Rails 5.2 with active storage. However, the Active Storage guide only provides instructions for uploads using built-in rails views. I'm now seeking ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

In Typescript, it is possible to assign properties to an object that are not explicitly defined in the object's type definition

I'm confused as to why Typescript isn't flagging this as an error... When I conditionally add a new property to an object that doesn't exist in the type definition, Typescript still allows it type Filters = { keywords: Array<stri ...

Stop materializecss dropdown from closing when clicking within it

As I work on my current project, I am utilizing Materialize.css which includes a dropdown with various input forms inside. The dropdown can be closed by: clicking outside of .dropdown-content clicking inside of .dropdown-content clicking on .dropdown-bu ...

What is the best way to invoke a class method within a promise in Angular 2?

When dealing with an Angular 2 component that retrieves data from a service in the form of an async promise or observable, how can one call a method within the component to display that data? @Component({ moduleId: module.id, selector: 'charts&ap ...

Troubleshooting: AngularJS not retrieving values from hidden input fields in ASP.NET MVC

I'm working on passing a list to a view as a hidden type and retrieving those values using Angular. for(int i = 0; i < Model.ListOfIds.Count;i++) { <input type="hidden" ng-model="model.ManagersId" value="@Model.ListOfIds[i]" /> / ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Is it necessary to sanitize strings before assigning them as the content of a textarea element?

Consider the situation described below: var evil_string = "..."; $('#mytextarea').val(evil_string); Is it necessary to sanitize an untrusted string before setting it as the value of a textarea element? While I am aware of the importance of han ...

Seeking assistance with transmitting data to the server and retrieving it for use. I am looking to achieve this goal utilizing JavaScript with Node.js

I've been experiencing challenges with the interactions between front-end and back-end. I am confident that I am sending the data, but unfortunately, I am unable to access it afterwards. Recently, I utilized this code template (sourced from Mozilla&ap ...

The chosen element contains a value of -1

When the select element has a selected value of 4, form data is sent to the server and the controller returns a partial view. <script> $(document).ready(function () { var objSel = document.getElementById("IDVacationApplicationTyp ...

ReactJS: Type error encountered - Unable to access property 'setState' as it is undefined

Currently, I am in the process of creating a compact weather application using reactJS from freecodecamp. Unfortunately, an error has arisen: "Uncaught TypeError: Cannot read property 'setState' of undefined." If you'd like to take a look ...

AngularJS: How to monitor variables without using $watch

I recently came to understand that Javascript operates on a "Call by sharing" principle, which means that everything is passed by value but the original contents of an object can still be modified. To illustrate this concept, consider the following scenari ...

Adjust the width of the dropdown menu for the v-combobox

I am currently working on creating a multiple search filter similar to the one found in Gitlab dashboard. https://i.sstatic.net/YHivl.png For this task, I am utilizing Vuetify's v-combobox like this : <v-combobox id="mycombo&quo ...

How to align a div in the center of a cell with Bootstrap

I am currently working with Bootstrap 3 and I have a specific requirement to center a div within a cell in the container row. Most resources I found only mention how to center a div within the entire container, which is not what I am looking for. My goal i ...

Troublication inquiry for retrieving the latest messages to and from User A experiencing issues with functionality

In my project, I have defined a model called MostRecentMessage, which looks like this: const MostRecentMessage = new Schema({ to: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, from: { type: mongoose.Schema.Types.ObjectId, re ...

Use Javascript's JQuery library to apply functionality to a newly inserted and cloned

I am facing an issue while trying to implement JQueryUI's DatePicker on a node. It works perfectly fine for all the existing nodes, but when I use the clone function to add new nodes, it doesn't seem to apply as expected. Here is the function th ...

The scrolling top value is dynamic when in developer mode

Looking to create a custom scrollbar for my web application. The approach I'm taking involves shifting the default scrollbar 100px to the right and hiding it with overflow:hidden in the parent container</p> $(".scrollbar-vertical").parent(). ...

I'm completely clueless as to what the issue might be - could it possibly

I need some assistance troubleshooting an issue I'm experiencing. When attempting to load my project in Chrome, all I see is a blank white screen. The code used to be in its own file and should display a cube with the help of jQuery and three.js once ...