Tips on incorporating a Google Plus +1 button in a Cordova/Ionic application

Incorporated a +1 button within my application: https://i.sstatic.net/1IHni.png

The code used:

<div class="g-plusone" data-size="tall" data-href="GOOGLE PLAY STORE LINK TO MY APP"></div>

also executed this script:

(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();

Ensured API access in the following files:

index.html:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com">

config.xml:

<allow-navigation href="https://apis.google.com" />

Encountered Issue: The functionality works on the browser (ionic serve) but fails within the app... Upon clicking, no action takes place... (no error prompts either)

Is there a feasible solution to make it function within the app? (ionic run)

Addendum/Debug Information:

  1. After selecting the +1 button on the web interface, it does not display the red button on the app ( Indicates shared link history and lack of user identification...)
  2. No intention to implement login/signup credentials, just aim to incorporate a +1 button...

If I insert:

<allow-navigation href="*" />

within config.xml, upon clicking the +1 button, a login prompt appears: (Not intended behaviour) https://i.sstatic.net/zAQWVl.png

Indicating that the +1 button remains non-functional due to being "in an anonymous browser", lacking authentication with the OS...

Pursued creation of a demonstration pure Android application adhering to these guidelines: https://developers.google.com/+/mobile/android/recommend Operating seamlessly... (+1 functionality present and functional...)

Tackling potential solutions:

  1. Implementing a native Android view embedding the +1 button into the webview.

  2. Crafting a pseudo +1 button which upon clicking, triggers a plugin invoking a request/action on the actual +1 button....

  3. Open to suggestions/input on resolving this situation?

Feasibility of either alternatives?

Appreciate your guidance!

Answer №1

It seems that the issue lies in the fact that the user is not logged into their Google account within the cordova browser, which is why a login prompt appears when trying to click the +1 button.

If you are looking to access the global Google account linked to the user's phone/OS and utilize it within your app, you will need to obtain credentials for accessing this data and ensure they can be accessed from the cordova browser. There is a helpful plugin available that can assist with this.

In your initialization code, you can use

window.plugins.googleplus.login(...)
to request user confirmation (if needed) and log in.

Ensure that the +1 button initialization occurs after logging in so that the correct state is displayed. Here is an example using jQuery:

$(document).ready(function() {
  loginToGoogle();
  initPlusOneButton();
}

function loginToGoogle() { ... }

function initPlusOneButton() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
}

Answer №2

Are you looking to avoid handling the login process? You can create a plugin to include a native PlusOneButton. I am currently developing this and plan to release it later today. Since moderators frown upon "link-only answers," I will explain here how to build the plugin and provide the link once it's completed.

Begin by reading the guide on building Cordova plugins; I won't delve into that level of detail.

Your CordovaPlugin subclass will require these variables:

private PlusOneButton mPlusOneButton;
private String URL;

Your execute method should look like this:

public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (action.equals("show")) { // show is what you call from JavaScript
        URL = "http://www.phonegap.es"; // retrieve from plugin parameters
        mPlusOneButton = new PlusOneButton(cordova.getActivity());
        mPlusOneButton.initialize(URL, null);

        // Ensure this part runs on the UI Thread
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                cordova.getActivity().addContentView(mPlusOneButton, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));

                // Position the button as desired, taking values from the plugin parameters
                mPlusOneButton.setX(300);
                mPlusOneButton.setY(300);
            }
        });

    } else {
        return false;
    }
    return true;
}

Finally, add the onResume method to keep the button status updated:

@Override
public void onResume(boolean multitasking) {
    super.onResume(multitasking);
    mPlusOneButton.initialize(URL, null);
}

The plugin must include the

com.google.android.gms:play-services-plus
dependency.

To do this, add the following line to the plugin.xml:

<framework src="com.google.android.gms:play-services-plus:+" />

UPDATE: The plugin is now available at https://github.com/jcesarmobile/plusOneButtonPlugin

To install it:

cordova plugin add https://github.com/jcesarmobile/plusOneButtonPlugin

To use it:

var params = {};
params.url = "http://www.example.com";
params.position = {x:100, y:100};
plusOneButton.show(params);

Or

plusOneButton.show("http://www.example.com");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The onClick event within the pageinit function only triggers once the page has been refreshed

Despite my attempts to search for a solution in existing duplicate questions, I have been unable to find one that fits my specific problem. Here's the issue at hand: I have a banner that appears on every page of my project. Within the banner, there a ...

Issues with rendering in Three.js CanvasRender: faces continuously flicker on and off

I am creating two relatively simple shapes that do not overlap in terms of their geometry. Below is the code snippet for reference: http://jsfiddle.net/pGD4n/9/ Within this code, there is a Three.js Trackball feature allowing you to click and drag to rot ...

Javascript inheritance through prototypes results in the addition of supplementary attributes within the descendant classes

When dealing with inheritance in JavaScript, I often encounter a issue where derived classes contain duplicate properties of the base class. And yet, I struggle to understand how to ensure that the derived class leverages the properties of the base class p ...

Why isn't my AJAX POST request to PHP functioning correctly?

It was all working perfectly fine earlier, but now something seems off and I must have made a mistake somewhere. I'm in the process of setting up a form where the information entered is sent via AJAX to my PHP file, which then outputs the username an ...

When using Cordova on Android, the getResponseHeader("Set-Cookie") function will only return the last cookie and not the entire list of cookies

When working with an Android platform in a Cordova project, the function getResponseHeader("Set-Cookie") only retrieves the last cookie from the response, unlike in the iOS platform where it retrieves all cookies. $.ajax({ type: "POST", cache:false, url: ...

Why is my canvas element not fully extending on the page even though I've set its scrollHeight property

Currently developing a browser extension for Chrome and Edge that adds a Canvas to any webpage, allowing me to draw rectangles. The Canvas should ideally stretch the entire scrollHeight of the page, but unfortunately falls short just before reaching the f ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...

The JQUERY Uncaught Error: Syntax error message popped up when trying to access an unrecognized expression on the javascript: void(0)

I've encountered an issue after upgrading to jQuery 3.4.1 while using bootstrap 3. The console keeps showing this error: Uncaught Error: Syntax error, unrecognized expression: # Here is the section of code causing the error: <div class="btn-grou ...

Learn how to toggle a React component with the help of Redux Toolkit

I'm facing an issue with toggling a React component using Redux Toolkit. I am unable to access the value of "toggle" as the useSelector in Redux Toolkit is returning "undefined". The code seems to be not functioning properly. I would appreciate any s ...

Obtaining the identifier of the grandparent element that is of the "

I'm working on a project where I have a dynamic element called .courseBox. It's an <li> element that will be placed within a <ul> container. Each .courseBox has a red "x" button that, when clicked, removes it from the <ul>. Here ...

Tutorial on Removing and Re-Adding HTML Elements

Currently, I am utilizing Jquery to temporarily remove an element from the DOM. This specific element consists of an HTML5 video element. However, upon re-adding this element back into the DOM, the video is unable to play and the element appears as blank o ...

What could be causing my PUT and DELETE requests to return a 404 status code?

I have encountered a problem with my MEN back-end app. In the express client router, I declared PUT and DELETE requests but they are returning a status 404 not found error. However, the POST request is functioning correctly. Could this ...

Why isn't the unit test passing when it clearly should be?

I am encountering an issue with testing a simple function that I have created. Despite the fact that the function works correctly in practice, it is not being tested properly... Explanation of how my function operates (While it functions as intended, the ...

What is the best way to concatenate two different values in React JSX using the "+" operator?

I have a situation where I need to take a value from an input, add 10% to it, and display the result. For example, if a person inputs 1000, the 10% of 1000 is 100, so the total result should be 1100. Currently, when I use the "+" operator, it concatenates ...

SetBootstrapTooltip at the location of the mouse pointer

Is it feasible to implement a bootstrap tooltip that follows the mouse cursor in AngularJS? If not, what other options are available for achieving this functionality? ...

How can I remove the script file from my req.params?

Can anyone help me figure out how to extract the :rid from my req.params without getting two values, one being the rid and the other the script file? Take a look at this screenshot from the console.log: console.log picture This is my route code: router. ...

Implementing CSS transitions across several elements simultaneously can enhance the user experience

There seems to be an issue with animating two elements simultaneously using max-height. The transition always occurs one after the other, with one element completing its transition before the other starts. setTimeout(function () { $(".b").css( ...

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Thumbnail Centering Issue in Swiper Plugin by iDangero.us

Currently, I am utilizing the Swiper plugin created by iDangero.us. Within my layout design, there are 6 slider images accompanied by 6 thumbnails. Surprisingly, when I attempt to center align the thumbnails, it appears to cause issues with the plugin. Th ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...