div onclick or oncontext is working only one time after webview load in cocoa div onclick or oncontext is working only one time after webview load in cocoa objective-c objective-c

div onclick or oncontext is working only one time after webview load in cocoa


Scope of this in javascript is pretty tricky, especially when binding DOM events. Instead of explicitly passing the param in your onClick function, we can use the natural click event to get the data you want:

You have:

<div class="msg" id="1" onClick="window.objcConnector.MsgDivClicked_(this.id)">

If we remove the parameter, the function call will have a scope where this is the element clicked. We could also substitute a parameter e which would be the MouseEvent of the click. Then we could get the element via e.target.

<div class="msg" id="1" onClick="window.objcConnector.MsgDivClicked_()">

Since you're calling an ObjectiveC function and not a JavaScript one, I'm not really sure how the natural scoping works. So instead, lets let a tiny bit of JS do the trick:

<script type="text/javascript">function objCClickHandler (e) {  window.objcConnector.MsgDivClicked_(this.id)}</script><div class="msg" id="1" onClick="objCClickHandler()">

You could also get rid of all the onClick handlers and just do this all in a script tag:

<script type="text/javascript">Array.from(document.querySelectorAll('.msg')).map(msg => {  msg.addEventLister('click', e => {      window.objcConnector.MsgDivClicked_(e.target.id)  })}</script>

Any element that you give a class of 'msg' to would then be wired up to click through to your app.