function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tylerotylero 

How do you get a webpage element from an external webpage?

I am trying to capture an element from an external webpage and display it on a visualforce page whenever the text value in a field exists as a value for the external webpage. For example, if I type "GOOG" in the text field, then the page should render the current price for Google's stock.

 

Here are the details of the task:

1. Create a field to enter the ticker symbol of a stock.

2. Use the inputted ticker symbol to render a call to Google Finance or Yahoo! Finance.

3. Return the quoted price on the webpage to the visualforce page in a field.

4. The page should rerender the current price every 10 seconds.

 

I currently have the following object and fields:

Object: Stock_SC__c

 

Fields:

1. Ticker_Symbol_SC__c = text field to capture the desired ticker symbol.

2. Google_Finance_Link_SC__c = formula field that concatenates the base website URL (http://www.google.com/finance?q=) and Ticker_Symbol_SC__c text field.

3. Yahoo_Finance_Link_SC__c = formula field that concatenates the base website URL (http://finance.yahoo.com/q?s=) and Ticker_Symbol_SC__c text field.

 

The element of Google finance that stores the current price is "<span id="ref_694653_l">1,033.89</span>." For Yahoo! Finance, the element is "<span id="yfs_l84_z">73.06</span>."

 

Any help is appreciated!

Best Answer chosen by tylero
izayizay

Hi Tylero,

 

Here is a small sample that I put together on how you can do this using XMLHttpRequest. This uses jQuery.

 

        <script type="text/javascript" src="{!$Resource.jquery-1.9.1.min.js}"></script>
        <script type="text/javascript">
            if (window.XMLHttpRequest) {                          // If XMLHttpRequest exists...
                xmlhttp = new XMLHttpRequest();                   // Code for IE7+, Firefox, Chrome, Opera, Safari
            } else {                                              // Otherwise...
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Code for IE6, IE5
            }
            function do_search() {
                var keyword = $("#input").val();
                xmlhttp.onreadystatechange = function () {// When done getting the data... Run this function
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var result = xmlhttp.responseText;//get the result
                        result = result.replace(/(\r\n|\n|\r)/gm,'');//clean the returned string
                        result = result.replace(/\//g, '');//clean the result string
                        var stockInfo = jQuery.parseJSON(result);//convert string to javascript object
                        //Display stock info...
                        var htmlString = "<p>Stock Data for : " + keyword + "</p>" +
                        "<p>l = " + stockInfo[0].l + "</p><p>c = " + stockInfo[0].c;
                        $("#info").html(htmlString);
                    }
                }
                //Get stock from info google xmlhttp.open("GET", "http://www.google.com/finance/info?q=" + keyword); xmlhttp.send(); }
            $(document).ready(function(){                 $("#searchBtn").click(function(){                     do_search();
                }
            }); </script>
        <input type="text" id="input" /><input type="button" value="search" id="searchBtn"/> <div id="info"></div>

All Answers

sguptasgupta
Option 1- You can use javascript,..XMLHttpRequest or jquery get to send your ticker to the desired URL and get theresponse, then you can traverse to the responsestring and get the price value and assign it to your visualforce field...

Option 2 - use apex method using http callout (HttpRequest) and return the price value...use actionfunction or call it directly from your command button as per your need...
izayizay

Hi Tylero,

 

Here is a small sample that I put together on how you can do this using XMLHttpRequest. This uses jQuery.

 

        <script type="text/javascript" src="{!$Resource.jquery-1.9.1.min.js}"></script>
        <script type="text/javascript">
            if (window.XMLHttpRequest) {                          // If XMLHttpRequest exists...
                xmlhttp = new XMLHttpRequest();                   // Code for IE7+, Firefox, Chrome, Opera, Safari
            } else {                                              // Otherwise...
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Code for IE6, IE5
            }
            function do_search() {
                var keyword = $("#input").val();
                xmlhttp.onreadystatechange = function () {// When done getting the data... Run this function
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var result = xmlhttp.responseText;//get the result
                        result = result.replace(/(\r\n|\n|\r)/gm,'');//clean the returned string
                        result = result.replace(/\//g, '');//clean the result string
                        var stockInfo = jQuery.parseJSON(result);//convert string to javascript object
                        //Display stock info...
                        var htmlString = "<p>Stock Data for : " + keyword + "</p>" +
                        "<p>l = " + stockInfo[0].l + "</p><p>c = " + stockInfo[0].c;
                        $("#info").html(htmlString);
                    }
                }
                //Get stock from info google xmlhttp.open("GET", "http://www.google.com/finance/info?q=" + keyword); xmlhttp.send(); }
            $(document).ready(function(){                 $("#searchBtn").click(function(){                     do_search();
                }
            }); </script>
        <input type="text" id="input" /><input type="button" value="search" id="searchBtn"/> <div id="info"></div>
This was selected as the best answer
Satish_SFDCSatish_SFDC
Well as quoted above you can use Javascript Ajax Calls or ApexCallouts.

Regards,
Satish Kumar
tylerotylero

Thank you for the code!

 

I have written the following so far:

 

<apex:page standardController="Stock_SC__c" tabStyle="Stock_Ticker__tab">
<!-- VF page to execute Web Service Call and get quotes for referenced ticker symbol. -->
<!-- Entering valid stock ticker should get current stock quote. -->
<!-- Re-render quote every 5 seconds. -->

<!-- Start of jQuery -->
<script type="text/javascript" src="{!$Resource.jquery-1.9.1.min.js}"></script>
<script type="text/javascript">
if (window.XMLHttpRequest){							//If XMLHttpRequest exists...
	xmlhttp = new XMLHttpRequest();						//Code for IE7+, Firefox, Chrome, Opera, Safari
} else {									//Otherwise...
	xmlhttp = ActiveXObject("Microsoft.XMLHTTP");				//Code for IE6, IE5
}
function do_search(){
	var keyword = $("#input").val();
	xmlhttp.onreadystatechange = function(){				//When done getting the data, run this function
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			var result = xmlhttp.responseText;			//Get the result
			result = result.replace(/(\r\n|\n|\r)/gm,'');		//Clean the returned string
			result = result.replace(/\/g, '');			//Clean the result string
			var stockInfo = jQuery.parseJSON(result);		//Convert string to javascript object
			//Display stock data
			var htmlString = "<p>Stock Data for : " + keyword + "</p>" +
			"<p>l = " + stockInfo[0].l + "</p><p>c = " + stockInfo[0].c;
			$("#info").html(htmlString);
		}
	}
	//Get stock data from Google Finance
	xmlhttp.open("GET", "http://www.google.com/finance/info?q=" + keyword);
	xmlhttp.send();
}
$(document).ready(function(){
	$("#searchBtn").click(function(){
		do_search();
	}}));
</script>
<input type="text" id="input"/><input type="button" value="search" id="searchBtn"/>
<div id="info"></div>
<!-- End of jQuery -->



    <apex:form id="form1">
        <apex:pageBlock title="Stock Quote" id="pb">
        
            <!-- Field to lookup ticker symbol -->
            <apex:pageBlockSection title="Ticker Lookup" columns="1" id="pbs1">
                <apex:inputField value="{!Stock_SC__c.Symbol_SC__c}"/>
            </apex:pageBlockSection>
            
            <!-- Quote from Web Service Call -->
            <apex:pageBlockSection title="Quote" columns="1" id="pbs2">           
                <apex:actionSupport event="onchange" rerender="blockToRerender"/>
                <!-- <apex:outputText value="Refreshes since submission: {!count}" id="counter"/> -->
        		<!-- <apex:actionPoller action="{!incrementCounter}" reRender="counter" interval="5"/> -->
            </apex:pageBlockSection>
         
            <!-- URLs for Google Finance and Yahoo! Finance -->
            <apex:pageBlockSection title="Links" columns="1" id="pbs3">
                <apex:inputField value="{!Stock_SC__c.Google_Finance_Link_SC__c}"/>
            </apex:pageBlockSection>
            
            <!-- Page Block Buttons -->
            <apex:pageBlockButtons >
            	<apex:commandButton action="{!save}" value="Save"/>
            	<apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>
            
        </apex:pageBlock>
    </apex:form>  
</apex:page>

I am getting an error when implementing your code and I can't figure out how to resolve it.

Save error: Syntax error.  Missing '}' on line 0

 

Will you please help with this?

 

Thank you!

tylerotylero

The code is good now. Unfortunately, my browser reports that Yahoo! and Google say "No 'Access-Control-Allow-Origin' header is present on the requested resource" therefore blocking access to Salesforce.com to get the data.

 

<apex:page standardController="Stock_SC__c" tabStyle="Stock_Ticker__tab">
<!-- VF page to execute Web Service Call and get quotes for referenced ticker symbol. -->
<!-- Entering valid stock ticker should get current stock quote. -->
<!-- Re-render quote every 5 seconds. -->

<!-- Start of jQuery -->
<apex:includeScript value="{!URLFOR($Resource.jQuery)}"/>
<script type="text/javascript">
if (window.XMLHttpRequest){						//If XMLHttpRequest exists...
	xmlhttp = new XMLHttpRequest();					//Code for IE7+, Firefox, Chrome, Opera, Safari
} else {								//Otherwise...
	xmlhttp = ActiveXObject("Microsoft.XMLHTTP");			//Code for IE6, IE5
}
function do_search(){
	var keyword = $("#input").val();
	xmlhttp.onreadystatechange = function(){			//When done getting the data, run this function
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			var result = xmlhttp.responseText;		//Get the result
			result = result.replace(/(\r\n|\n|\r)/gm,'');	//Clean the returned string
			result = result.replace(/\//g, '');		//Clean the result string
			var stockInfo = jQuery.parseJSON(result);	//Convert string to javascript object
			//Display stock data
			var htmlString = "<p>Stock Data for : " + keyword + "</p>" +
			"<p>l = " + stockInfo[0].l + "</p><p>c = " + stockInfo[0].c;
			$("#info").html(htmlString);
		}
	}
	//Get stock data from Yahoo! Finance
	xmlhttp.open("GET", "https://finance.yahoo.com/q?s=" + keyword);
	xmlhttp.send();
}
$(document).ready(function(){
	$("#searchBtn").click(
		function(){	do_search()}
	)});
</script>
<input type="text" id="input"/><input type="button" value="search" id="searchBtn"/>
<div id="info"></div>
<!-- End of jQuery -->



    <apex:form id="form1">
        <apex:pageBlock title="Stock Quote" id="pb">
        
            <!-- Field to lookup ticker symbol -->
            <apex:pageBlockSection title="Ticker Lookup" columns="1" id="pbs1">
                <apex:inputField value="{!Stock_SC__c.Symbol_SC__c}"/>
            </apex:pageBlockSection>
            
            <!-- Quote from Web Service Call -->
            <apex:pageBlockSection title="Quote" columns="1" id="pbs2">           
                <apex:actionSupport event="onchange" rerender="blockToRerender"/>
                <!-- <apex:outputText value="Refreshes since submission: {!count}" id="counter"/> -->
        		<!-- <apex:actionPoller action="{!incrementCounter}" reRender="counter" interval="5"/> -->
            </apex:pageBlockSection>
         
            <!-- URLs for Google Finance and Yahoo! Finance -->
            <apex:pageBlockSection title="Links" columns="1" id="pbs3">
                <apex:inputField value="{!Stock_SC__c.Google_Finance_Link_SC__c}"/>
            </apex:pageBlockSection>
            
            <!-- Page Block Buttons -->
            <apex:pageBlockButtons >
            	<apex:commandButton action="{!save}" value="Save"/>
            	<apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>
            
        </apex:pageBlock>
    </apex:form>  
</apex:page>

 

izayizay

Here is an article that may help you solve this problem. Cross Domain Ajax Request