GithubHelp home page GithubHelp logo

jaanauati / react-dfp Goto Github PK

View Code? Open in Web Editor NEW
127.0 7.0 53.0 1.98 MB

A React implementation of the Google DFP/GPT api. https://react-dfp.surge.sh

License: MIT License

JavaScript 100.00%
dfp gpt reactjs advertising es6

react-dfp's Introduction

React DFP · Build Status Minizipped size GitHub license

A React implementation of the google DFP API. This package is inspired in the awesome library jquery.dfp, and aims to provide its same ease of usage but, of course, taking into consideration the react concepts & lifecycle features.

Installation:

To install just run the following command (no other dependencies are required):

npm install --save react-dfp

or

yarn add react-dfp

You can find more details in the React-dfp site.

Getting started

React-dfp has been designed in a very React-ish way, its main goal is to be able to serve DFP ads in your React application just using React components, which means that you won't have to programmatically perform any initialization call when your page loads.

Here a quick example, notice that ads will render in your page as soon as your component is mounted, through its components (DFPSlotsProvider and AdSlot), react-dfp is making a full abstraction of the google dfp/gpt API.

import React, { Component } from 'react';
import { DFPSlotsProvider, AdSlot } from 'react-dfp';
...
class Page extends Component {
   render() {
     ...

     return (
        <DFPSlotsProvider>
         ...
         <AdSlot adUnit="home/leaderboard" sizes={[ [900, 90], [728, 90]]} />
         ...
         /* you can override the props */
         <AdSlot adUnit="home/mobile" sizes={[ [300, 250], [300, 600]]} />
         ...
         <div>
           ...
           <AdSlot adUnit="home/footer" sizes={[ [300, 250], [300, 600]]} />
           ...
         </div>
         ...
       </DFPSlotsProvider>
     );
   }
}

Examples

See the React-dfp site for more examples (basic example, how to have refreshable ads, etc).

Documentation

You can find the React-dfp documentation on the website. The site is divided into many sections that describe each one the Components, properties and also the DFPManager API (in case you need to use this one manually).

The website is also full of live/working examples.

You can find the source code of the website here: https://github.com/jaanauati/react-dfp-website.

Wanna help?

I certainly know that test cases need to be improved, but, as long as your syntax is clean, submit test cases and, of course, all the interfaces are kept working, all kind of contribution is welcome.

Complaints.

Pull requests are welcome 🍻.

react-dfp's People

Contributors

adamgrov avatar barelyfitz avatar daraclare avatar dependabot[bot] avatar dorom avatar duffman85 avatar jaanauati avatar jeffersonlicet avatar kant avatar marcosvlehmkuhl avatar nirarazi avatar patrick-mcdougle avatar rvgpl avatar scott-thrillist avatar scottydev avatar sl-pierrevautherin avatar wallaka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-dfp's Issues

Ads not displaying: Preload message in console

My ads are not displaying. I am using a very basic code, much like the first example in the documentation. I am recieving the following message in my console.

The resource http://pagead2.googlesyndication.com/pagead/js/r20181128/r20180604/show_ads_impl.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.

Any help is greatly appreciated!

DFPManager.load(slotId) does not limit loaded slots to the slotId argument

The issue is that DFPManager.load(slotId) loads every slot, not just the one with the given slot id as expected.

These lines seems like they may be the cause of the issue https://github.com/jaanauati/react-dfp/blob/master/js/manager.js#L160-L167

    if (loadAlreadyCalled === true) {
      const slot = registeredSlots[slotId];
      if (slot !== undefined) {
        availableSlots[slotId] = slot;
      }
    } else {
      availableSlots = registeredSlots;
    }

It seems that the available slots are only limited to the given slotId if loadAlreadyCalled is true. Is this intentional or a bug? If intentional, how can I load a single slot?

There no exist documentation about interstitial

In js/manager.js exist a property called renderOutOfThePage and it could be implemented in the AdSlot component (with the issue that returns an iframe with a width 1px and height 1px)

I don't know if it's an issue at all. But I need to implement this feature with the atributes width 100% and height 100% and I really don't know how to contribute with that.
Thanks.

Blank adunit single page application on page updates

This could be a DFP issue. If anyone has any ideas that would be great. Or experienced the issue.

I have tried a number of things including removing "googletag.pubads().enableSingleRequest();" from manager.js which I saw referenced in DFP forums.

When either paging through results (react app requests next page of results via api and updates state), or switching from one container to the other (using redux). I get empty responses from DFP. If you page VERY slowly the ads will populate. Its behaves like its throttled but I cannot find any reason or setting for it anywhere. (first try of dfp).

CI / tests

  • run unit tests when new code is pushed.
  • lock a branch if tests fail.
  • research: is it possible to release when new code gets merged into master???

Feature Request - setRequestNonPersonalizedAds

Hi. With the new European data protection law, I have needed to make some adjustments with the advertising sample depending on the acceptance of consent. You could add an attribute to control custom ads.

Thanks for your work, it has helped me a lot with my project.

Implementing activity tags

Hi! I'm trying to implement this code, but I have no idea how to do it with this lib:

<script type='text/javascript'>
var axel = Math.random()+"";
var a = axel * 10000000000000;
document.write('<img src="https://pubads.g.doubleclick.net/activity;xsp=4453085;ord='+ a +'?" width=1 height=1 border=0>');
</script>

<noscript>
<img src="https://pubads.g.doubleclick.net/activity;xsp=4453085;ord=1?" width=1 height=1 border=0>
</noscript>

It refers to the following article: https://support.google.com/admanager/answer/2499318?hl=en

Any help would be great.

Thanks!

adSenseAttributes is not working

I've update the version to 0.6.0 but the adSenseAttributes is not printing my site_url

<DFPSlotsProvider
        targetingArguments={data}
        sizeMapping={sizeMapping}
        adSenseAttributes={{ "page_url" : "HelloURL" }}
        collapseEmptyDivs={false}
      >
        <AdSlot
          ref={adSlot => {
            this.adSlot = adSlot;
          }}
          sizes={sizes}
          adUnit={adUnit}
          shouldRefresh={() => true}
        />
      </DFPSlotsProvider>

Can control responsive view using sizemapping?

I wanted to control responsive view by using sizemapping, something like,

export const GOOGLE_ADS_SIZEMAPPING_MEMBER_PROFILE_MOBILE = [
  { viewport: [960, 300], sizes: [[300, 100], [200, 200], [300, 250], [250, 250]] },
];

^^ In this i wanna hide ads for viewport larger than 960px.

Note: I do use CSS to control the responsive view, but the problem is at user level the ads are hidden but the scripts are still loading.

Lots of postMessage in not a function error in mobile Safari

Hi,
I've started to show dpf in my web a few days ago using react-dfp and I'm seeing a bunch of postMessage in not a function error in my logs. All error appears to be coming from the adsense script and almost all of them comes from mobile Safari, so I don't think is a react-dfp issue, but maybe someone around here can know why are this error happening or if there is something I can do to prevent them from happening.

Thanks for this amazing module by the way!

Auto-Refreshing just 2 of the 4 ad units on page

This below refreshes all ad units on a 15 second interval. What if we have a total of 4 ad units and we only want to refresh 2 of them specifically on a time interval?

// refresh ads every 15 seconds
window.setInterval(function refreshAds() { DFPManager.refresh(); }, 15000);

Really appreciate the work you've done here.

DFPManager vs DFPSlotsProvider

Hi, I'm having problems understanding the differences between DFPSlotsProvider and DFPManager, I can see in the examples of the readme that they aren't being used both at the same time.

Does this mean DFPManager doesn't need a slot provider? Could you provide a simple example using each of them for the same task?

I'm trying to figure out how to lazy load ads on page load and I'm wondering which one is better to use and what the differences are.

Consider deleting examples directory from published package

Hey there!

I was just doing an audit of our Node project. Please consider deleting the examples directory when publishing, or only publishing a subset of the files in this repo. The examples directory adds 10MB no-one installing this package will ever use.

screen shot 2018-11-27 at 3 33 56 pm

AdSense 403

Hello.

Obviously, some of you have succeeded in getting AdSense through DFP calls.

I have implemented an AdSense campaign in DFP (maybe there is a better way of doing this).

When I call the , I get a correct Ad if DFP returns an ad which is not AdSense but I get a 403 if it returns an AdSense Ad. I've tried to pass "page_url" with the URL of the website where ads are currently displayed but with no luck.

Any help would be greatly appreciated.

DFPSlotsProvider adUnit not updating in the DOM

Hey, I'm having trouble updating the adUnit slot before running DFPManager.refresh()

If you set the DFPSlotsProvider and/or AdSlot adUnit to refresh based on an updated container state, you can see the actual props for these two components update, but the AdSlot rendered html does not update in the DOM.

For example, going from 'home/category1' to 'home/category2' seems to update the components props, but it doesn't update correctly in the DOM. Is there something I'm missing, do you need to completely destroy the ad units and then recreate them with the new adUnit prop?

After the react-dfp components have updated, running DFPManager.getRefreshableSlots() will still show the previous adUnits, e.g. 'home/category1'. Running DFPManager.refresh() will just refresh with the original adUnit.

Passing down AdSlot to Child Components

Using AdSlot in a child component causes a problem and it affects all AdSlot components all around the page. Is there a way to pass down AdSlot to the child components as a prop or defining AdSlot into child components without declaring DFPSlotsProvider?

DFPSlotsProvider already declared in the parent component and also we can use only one DFPSlotsProvider into the page.

 <DFPSlotsProvider dfpNetworkId={adNetworkID}>
        <AdSlot
          sizes={[[970, 250]]}
          adUnit={"AnasayfaMastHead"}
          slotId="anasayfaMastHead"
        />
        <AdSlot
          sizes={[[160, 600], [120, 600]]}
          adUnit={"anasayfa_sol1"}
          slotId="anasayfa_sol"
        />

        <Block type="main">
              <Article
                title={title}
                desc={description}
                cat={breadcrumbs.cat.title}
                catUrl={breadcrumbs.cat.url}
                className="main-article"
                cover={haber_gorsel[0]._id}
                isSSR={true}
                content={haber_metni}
                slot={ { <AdSlot /> } } // or inside this component
              >
                <CardManager
                  dataset="cat-gundem"
                  limit={2}
                  vertical={true}
                  cardBg="#282841"
                  className="section-cards__sag-manset-yani"
                  imgClassName="nomargin"
                  border="#ffa200"
                  width={303}
                  lineHeight="24"
                  textColor="#fff"
                  slot={ { <AdSlot /> } } // or inside this component
                />
                <AdSlot
                  sizes={[[970, 120]]}
                  adUnit={"HaberDetay_970x250"}
                  slotId="HaberDetay_970x250"
                />
              </Article>
            </Block>
      </DFPSlotsProvider>

It shows undefined as the rendered component?

Hey,

I tried to implement this in my app. But an undefined component is rendered instead.
Can i get a proper example for this. I have implemented dfp already in my app. But sometimes the ads won't render (blank ad is shown instead).
So i wish to switch to this implementation. Can you help?

Thanks.

Receiving Exception in queued GPT command TypeError in console when loading ad.

I receive the following error intermittently when displaying an ad unit:

Exception in queued GPT command TypeError: Cannot read property 'addService' of null

screen_shot_2017-02-24_at_3 06 39_pm 1

The ad still shows with no issues but I'd like for my console to be clean. Here is the code for the component using the ad.

import React from 'react'
import { AdSlot, DFPManager } from 'react-dfp'
import { AboveTheFoldOnlyServerRender } from 'above-the-fold-only-server-render'

const AdDfp = props => {
  return (
    <AboveTheFoldOnlyServerRender skip>
      <div>
        <AdSlot sizes={props.viewports} adUnit={props.adUnit} dfpNetworkId={props.dfpNetworkId} />
        {DFPManager.load()}
      </div>
    </AboveTheFoldOnlyServerRender>
  )
}

export default AdDfp

I'm having trouble figuring out if its related to implementation or if its a bug with react-dfp. Please offer any information you have about this.

autoLoad is not working

Hey there. Just checking the slotsprovider, the react prop autoLoad is not being used.
Are you planning to make this feature available?

Thank you.

nextjs build+export

(node:35459) UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
    at doloadGPTScript (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/utils.js:9:3)
    at /Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/utils.js:29:5
    at new Promise (<anonymous>)
    at Object.loadGPTScript (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/utils.js:28:10)
    at EventEmitter.getGoogletag (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/manager.js:132:42)
    at EventEmitter.init (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/manager.js:92:12)
    at EventEmitter.doLoad (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/manager.js:155:10)
    at EventEmitter.load (/Users/jonatan/projects/react-dfp-surge/node_modules/react-dfp/lib/manager.js:148:26)
    at Module.<anonymous> (/Users/jonatan/projects/react-dfp-surge/.next/server/static/i0iUOVpMWpyfeE9xt0Qwf/pages/basic.js:230:54)
    at __webpack_require__ (/Users/jonatan/projects/react-dfp-surge/.next/server/static/i0iUOVpMWpyfeE9xt0Qwf/pages/basic.js:23:31)

contributors

  • add list of people that have contributed anyhow to the project to readme.md
  • show contributors under the npm 'collaborators' block (just read-only, people should not have write access, not sure if this is possible).

collapseEmptyDivs not working?

collapseEmptyDivs not working. Help me please?

<DFPSlotsProvider dfpNetworkId='4519939' collapseEmptyDivs={true}> <AdSlot adUnit={"4519939/deneme_300x250"} sizes={[[300, 250]]}/> </DFPSlotsProvider> <DFPSlotsProvider dfpNetworkId='4519939' collapseEmptyDivs={true}> <AdSlot adUnit={"4519939/deneme_300x600"} sizes={[[300, 600]]} /> </DFPSlotsProvider> <DFPSlotsProvider dfpNetworkId='4519939' collapseEmptyDivs={true}> <AdSlot adUnit={"4519939/deneme_300x250_2"} sizes={[[300, 250]]} /> </DFPSlotsProvider>

Auto-generated slot IDs are not always unique

I have 4 <AdSlot />s next to each other and when each one generates its own slot ID, quite frequently, the same ID gets generated for more than one <AdSlot />. This causes the slots to fail to register with DFPManager which causes those slots to fail to load at all.

I've worked around this issue by manually specifying slotId for each <AdSlot />.

enableSingleRequest not working on load

enableSingleRequest is not enabled on the initial request. I am seeing individual requests for each ad. Subsequent refreshes have single request enabled

import { DFPSlotsProvider, AdSlot } from 'react-dfp';
...
<DFPSlotsProvider dfpNetworkId={'9999'} adUnit={"foo/bar/baz"} >
    <AdSlot sizes={[ [900, 90], [728, 90]]} />
    <AdSlot sizes={[ [300, 250], [300, 600]]} />
</DFPSlotsProvider>

Feature Request - refresh individual slot

It would be really useful if we could refresh individual slots using DFPManager.refresh([slotId]) in the same way as can be done with DFPManager.load()

I have tried to achieve this by using googletag directly like so, however have not had any luck (maybe I'm missing something here?)

const slotId = 'adSlot-1';

DFPManager.getGoogletag().then((googletag) => {
  googletag.cmd.push(() => {
    googletag.pubads().refresh(DFPManager.getRefreshableSlots()[slotId].gptSlot);
  });
});

Feature Request - Render Sync and Single Request

Hey! First of all, thanks for your project!

I have one question, is there any posibility to be able to add support for syncRender and singleRequest? Or there is existent support for those?

Would you be able to accept a PR?

Show Cases

There's show cases?

It's safe for production? And with SSR?

About setTargeting from the manager.js

I would like to ask if it is possible to add the following code

    this.getGoogletag().then(function (googletag) {
      googletag.cmd.push(function () {
        pubadsService = googletag.pubads();
        Object.keys(globalTargetingArguments).forEach(function (varName) {
          pubadsService.setTargeting(varName, globalTargetingArguments[varName]);
        });
      });
    });

after
line 28 - _extends(globalTargetingArguments, data);

So that we can use DFPManager.refresh(); with a new targeting arguments.

Error when unmounting and ad is not shown

First time using Google Ads and DFP, so not exactly sure where the problem is.
But when changing route in our app, I get this kind of error:

Uncaught TypeError: Cannot read property 'gptSlot' of undefined
    at manager.js:312
    at Array.map (<anonymous>)
    at EventEmitter.destroyGPTSlots (manager.js:311)
    at EventEmitter.unregisterSlot (manager.js:361)
    at AdSlot.unregisterSlot (adslot.js:142)

It looks like this happens because manager. registeredSlots has entries that do not (yet?) have gptSlot.

I presume that gptSlot is somehow given in async way, which leads to this error, but I could be wrong..

DFP Provider overriding AdSlot Sizes

First off, great component! Well designed API and easy to use especially as I'm learning DFP. Works like a react component should.

Here's an issue I'm running into, and I don't know if it's my understanding of the DFP, or what.

I built an AdUnit component using this, here it is:

import React, { PropTypes as PT } from 'react';
import { DFPManager, DFPSlotsProvider, AdSlot } from 'react-dfp';
import Interval from 'react-interval';

const AdUnit = props => (
  <section className={`ad-unit tc ${props.classString}`}>
    <h5 className="p0 ttu sans-serif fw2 mb2">advertisement</h5>
    <Interval
      enabled={props.enableRefresh}
      timeout={props.rate * 1000}
      callback={() => { DFPManager.refresh(); }}
    />
    <DFPSlotsProvider
      dfpNetworkId={props.dfpId}
      targetingArguments={props.targeting}
      sizeMapping={[
        { viewport: [768, 0], sizes: [[728, 90]] },
        { viewport: [0, 0], sizes: [[320, 50], [300, 50]] }]}
    >
      <AdSlot
        dfpNetworkId={props.dfpId}
        adUnit={props.tag}
        sizes={props.sizes}
        shouldRefresh={() => (props.enableRefresh)}
      />
    </DFPSlotsProvider>
  </section>
);

AdUnit.propTypes = {
  tag: PT.string.isRequired,
  targeting: PT.object,
  classString: PT.string,
  dfpId: PT.string.isRequired,
  rate: PT.number,
  sizes: PT.arrayOf(PT.array),
  enableRefresh: PT.bool,
};

AdUnit.defaultProps = {
  dfpId: 'REDACTED',
  rate: 30,
  enableRefresh: false,
  sizes: [[300, 250], [320, 50], [300, 50]],
};

module.exports = AdUnit;

So the DFPSlotsProvider defines what sizes of ads can be displayed at what viewport, but the sizes in the AdSlot should show up in that particular slot, correct?

I have overridden my "sizes" in the AdSlot to NOT include [300, 250], but they are still showing up in the AdSlot.

Any ideas why that might be happening?

Regardless, thanks for your help and your work on this great component.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.