Jorge
Jorge

Reputation: 83

Taking the result from a function and adding it to a javascript

I am using a JavaScript that reads the URL and parses the parameters. The JavaScript works just fine when I add a document.write to the body of the page. I am trying to take a parameter value and populate it into a Google JavaScript for ad serving. It would be ideal to take the parameter 'fire' from the 'frank' variable and replace it with 'VALUE' located in this JS: GA_googleAddAttr("ad_key", "VALUE");.

I feel as though I am missing something taking the result from the first JS and making it available for placement in the Google JS.

Any help will be greatly appreciated. Thank in advance.

Example URL: http://www.example.com/test.html?frank=fire

------------ JavaScript: get url parameter ------------

<script type="text/javascript">

function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )    return "";
else    return results[1];}

var frank_param = gup( 'frank' );

</script>

------------ JavaScript: google ad serving attribute ------------

<script type="text/javascript">
GA_googleAddAttr("ad_key", "VALUE");
</script>

ad_key = Added within the Google DFP ad serving platform

VALUE = Used for targeting ads for a specific page


Upvotes: 0

Views: 173

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120546

The first script does a bunch of unnecessary work and is subtly incorrect.

It will fail

  1. when the parameter name contains a back slash
  2. when there is no parameter in the query but there is one in the fragment
  3. when the parameter value contains a %-encoded character

You can replace it with

function gup(name) {
  var params = {};
  var parts = (window.location.search || '').split(/[&?]/);
  for (var i = 0; i < parts.length; ++i) {
    var eq = parts[i].indexOf('=');
    if (eq < 0) continue;
    params[decodeURIComponent(parts[i].substring(0, eq))]
        = decodeURIComponent(parts[i].substring(eq+1));
  }
  return Object.hasOwnProperty.call(params, name)
      ? params[name] : null;
}

which will correctly get you a CGI parameter value.

Then just follow it with

GA_googleAddAttr("ad_key", gup('frank') || '');

Upvotes: 1

Leo
Leo

Reputation: 5286

GA_googleAddAttr("ad_key", frank_param); should do the trick.

Upvotes: 0

Related Questions