Sunil Soni
Sunil Soni

Reputation: 443

Why Javascript code executes in the ko.observableArray();

I have an issue, I am reading the files from google drive and listing on the page using knockout.js. I am using the observable array to store file data file data includes various parameters of the file like name, size, and link etc.

I am creating the JSON object and the push to the array. but here is the main issue. if the file name contains the javascript code like

<script>alert('i am executing');</script>

then it executes and show the alert message

here are some details

var file = {
  Name: <script>alert('message')</script>,
  URL: item.alternateLink,
  ServerRelativeUrl: item.alternateLink,
  modified: item.modifiedDate,
  icon: item.iconLink
};

docs.push(file);

is there anyone facing the same issue or have a solution to prevent unwanted script executions

Upvotes: 0

Views: 35

Answers (1)

H77
H77

Reputation: 5967

Since you're using html to bind the property Name, any javascript code in the property will be executed by the browser. To prevent this you should use text instead of html to bind the data. This will encode any HTML preventing script injection.

e.g.

<p class="summary">
   <a target="_blank" data-bind="text:Name, attr:{href:URL}"></a>
</p>

Upvotes: 1

Related Questions