Cross-origin object when everything is coming from localhost

Viewed 298

I'm trying to record every time a user changes a text input on my web page. I'm using the following:

function formInit(socketObject) {
  $('input:text').change( (eventObject) => {
    console.log(document.domain);
    console.log(JSON.stringify($(this)));
    //... send stuff via socketObject
  });
}

which I'm calling from $(document).ready(). I'm getting the following error on that fourth line, the one that logs $(this):

SecurityError: Permission denied to access property "toJSON" on cross-origin object

despite the fact that console.log(document.domain); returns localhost from both the script and from the master document it's being called from. The only thing that isn't being served up from my flask server on localhost are a couple of libraries (jquery, socketio, cleave) and possibly some components in a bokeh chart, which I'm pretty sure don't qualify as input:text, and certainly haven't been the thing I've been .change()ing in my debugging.

Can anyone suggest where I'm going wrong here, or where I should be looking? Thanks.

1 Answers

The error is because this is not the input:text element as you seem to be expecting, because you're using an arrow function, so lexical scope is not maintained. You either need to change the arrow function to an anonymous function:

function formInit(socketObject) {
  $('input:text').change(function() {
    // 'this' now refers to the element which raised the event
  });
}

Alternatively keep the arrow function, but get a reference to the element from the event which is raised and provided as an argument to the handler function:

function formInit(socketObject) {
  $('input:text').change(e => {
    // 'e.target' now refers to the element which raised the event
  });
}

Aside from the error, stringifying an entire jQuery object is a little odd. It's a better idea to just pull out only the relevant properties you need, something like this:

function formInit(socketObject) {
  $('input:text').change((e) => {
    console.log(document.domain);
    console.log({
      id: e.target.id,
      value: e.target.value
      // other properies here...
    });

    // send stuff via socketObject...
  });
}
Related