Created
January 21, 2019 12:53
-
-
Save Sherbin/5aec711a07d1ae04f40c0ae3de1d8c51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>To send command into some widget we use PostMessage (https://developer.mozilla.org/ru/docs/Web/API/Window/postMessage)<br> | |
Way to find required <iframe> is option "id" passed for initialization</p> | |
<p>Javascript and further HTML is Exapmle</p> | |
<p>NOTE: We use this tricky way because we need to handle all widgets the same. Both initialized with tv.js (https://www.tradingview.com/widget/advanced-chart/) and initialized self-replaced script (https://www.tradingview.com/widget/technical-analysis/)</p> | |
<!-- Example start --> | |
<!-- Advanced chart widget initialization --> | |
<div id="advanced-chart-widget-container"></div> | |
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script> | |
<script type="text/javascript"> | |
window._tvEmbedWidgetAdvancedChart = new TradingView.widget({ | |
"id": "tv-embed-widget-advanced-chart", // this string will be set as as id attribute to <iframe> | |
"allow_symbol_change": true, | |
// some options | |
"container_id": "advanced-chart-widget-container" | |
}); | |
</script> | |
<!-- Advanced chart widget initialization --> | |
<script> | |
function whenDocumentReady(cb) { | |
var isIE = ('attachEvent' in document); | |
var isDocumentReady = isIE ? document.readyState === 'complete' : document.readyState !== 'loading'; | |
if (isDocumentReady) { | |
cb(); | |
} else { | |
document.addEventListener('DOMContentLoaded', cb); | |
} | |
} | |
whenDocumentReady(function() { | |
var elIframeWidget = null; | |
function setSymbol(symbol) { | |
if ( | |
!elIframeWidget || | |
!elIframeWidget.contentWindow | |
) { | |
return; | |
} | |
elIframeWidget.contentWindow.postMessage( | |
{ | |
name: 'set-symbol', | |
data: { | |
symbol: symbol, | |
}, | |
}, | |
'*' | |
); | |
} | |
window.addEventListener('message', function (event) { | |
var data = event.data; | |
if (data.name === 'tv-widget-load') { | |
if (data.frameElementId === 'tv-embed-widget-advanced-chart') { // NOTE: was passed in initialization | |
elIframeWidget = document.getElementById('tv-embed-widget-advanced-chart'); | |
if (!elIframeWidget) { | |
console.error('Advanced Chart widget iframe not found'); | |
} | |
} | |
if (elIframeWidget) { | |
window.setSymbol = setSymbol; | |
console.info('Function "setSymbol" is available in console.\nUsage: "setSymbol(\'TSLA\')"'); | |
} | |
} | |
}); | |
}); | |
</script> | |
<!-- Example end --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tradingview documentation is shit, but you're the real hero!