Tips for creating a permission dialog for posting messages on a wall

I have developed a Facebook application using the Facebook JavaScript SDK and Android PhoneGap. I am able to post messages to the Facebook wall, but now I want to include a permission dialog before posting the message. The goal is to only allow the message to be posted if the user clicks on the "Allow" button in the permission dialog; if they click on "Don't Allow," the message should not be posted. Here is the code snippet:

<body>
<div id='fb-root'></div>
<script src='all.js'></script>
<input type="text" value="User ID" name="user_ids" />
           <p><a onclick='postToFeed(); return false;'>Post to Feed</a></p>
            <p id='msg'></p>
    <script> 
      FB.init({appId: "xxxxxxxx", status: true, cookie: true});

      function postToFeed() 
    {
                    var user_ids = document.getElementsByName("user_ids")[0].value;
                   alert(user_ids);

                    FB.api('/me/feed', 'post', { message: user_ids}, function(response) {
                           if (!response || response.error) {
                            alert('Error occured');
                           } else {
                           alert('Post ID: ' + response.id);
                           }
                   });
      }
   </script>
  </body>

The above code is currently hosted on a server. In the PhoneGap (index.html) app, I call this URL using the window.open method. When the button is clicked (and the text value from the textbox is retrieved), the message should be posted on the wall. Now, I am looking for suggestions or ideas on how to implement a permission dialog for this functionality or how to pass {perms:'publish_stream'} in the FB.api('/me/feed') call.

Any help or suggestions would be greatly appreciated. Thank you.

Answer №1

It's possible that I may not fully understand your question, but here is a suggestion: Firstly, seek permission before proceeding to display the send button or automatically send a post - choose one option, not both simultaneously (the concept seems unclear to me). Below is some code snippet that might be of assistance:

window.fbAsyncInit = function() {
    FB._https = true;
    FB.init({
        appId : 'YOUR_APP_ID',
        status : true, 
        cookie : true, 
        oauth : true 
    });

    // Check if user is connected to the app
    FB.getLoginStatus(function(response) {
        if (response.status !== 'connected') {
            // User has not authorized the app
            authorizeApp();
        } else {
            // User has already authorized the app
            var fbuid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            
            FB.api('/me', function(response) {
                // Check for publish_stream extended permission
                var query = FB.Data.query('select publish_stream from permissions where uid={0}', fbuid);
                
                query.wait(function(rows) {
                    if(rows[0].publish_stream == 1) {
                        // User has granted the extended permission
                        postToWall();
                    } else {
                        // User has not granted the extended permission
                        authorizeApp();
                    }
                });
            });
        }
    });
};

(function() {
    var e = document.createElement('script');
    e.type = 'text/javascript';
    e.src = document.location.protocol + '//connect.facebook.net/de_DE/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());

function authorizeApp() {
    // Redirect user after authorization
    var path = 'https://www.facebook.com/dialog/oauth?';
    var queryParams = ['client_id=YOUR_APP_ID', 'redirect_uri=REDIRECT_URI', 'response_type=token', 'scope=publish_stream'];
    var query = queryParams.join('&');
    var url = path + query;
    
    top.location.href = url;
}

// Alternate method
function authorizeAppInPopup() {
    FB.login(function(response) {
        if (response.authResponse) {
            // User authorized the app
            postToWall();
        } else {
            // User cancelled login or did not fully authorize
        }
    }, {scope: 'publish_stream'});
}

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

Avoiding the display of file picker dialog - Selenium GeckoDriver

Currently, I am attempting to use Selenium to upload a file by sending keys (the file path). While this method is successful in uploading the file, it also triggers the file picker dialog which remains open indefinitely. Although no actual issues occur, wh ...

Issue with rendering in React was encountered

I am a newbie in react and I want to display each new message, but in the render function I need to set an index in render_mess to show messages from an array. Is there a way to display all the elements without using a loop? class New extends React.Compon ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

beforeSend method in jquery ajax synchronously calling

One of my functions is called: function callAjax(url, data) { $.ajax( { url: url, // same domain data: data, cache: false, async: false, // use sync results beforeSend: function() { // show loading indicator }, ...

Creating a service function (constructor) in JavaScript

When working with AngularJs and calling a service method: app.service('nameService', function() { this.Service = function (){console.log('hello')} } You can then use this service (object) like so: nameService.Service() My question is, ...

`Close a bootstrap alert by clicking anywhere outside of it`

Bootstrap Warnings Image Two types of bootstrap alerts are present - warning and danger. Danger alerts always remain on the page, while warning alerts pop up when the user clicks on the dropdown list for carriers, displaying a notification. The user can cl ...

Issue with Collapse Feature on Bootstrap 3.x Navbar

The Bootstrap 3 Navbar expands properly in full screen and on a browser with a small width on a desktop PC and mobile browsers, but when using the Toggle navigation button, it doesn't slide down. I have tried to replicate the code from this example: h ...

Interactive calendar feature displaying events upon hovering over a date

I need some assistance with displaying a drop-down list on full calendar events when hovering over the events. Can someone provide guidance? Here is a glimpse of what I currently have: https://i.sstatic.net/fZXMH.png I've attempted setting the z-in ...

Performing multiple jQuery $.post() requests recursively

My confusion with jQuery arises in a specific scenario: When I run this code in debug mode, everything works perfectly fine. However, when running the code normally, the callback function fails to execute. Why does this happen? In non-debug mode, the sequ ...

Transform URL in AngularJS Service

An issue I'm facing with the app I'm developing is that users need to be able to change the IP address of the server where the REST API is hosted. The challenge lies in the fact that while the address is stored in a variable that can be changed, ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

What could be the reason a normalMap fails to render accurately while utilizing THREE.SubdivisionModifier?

When attempting to render a 'soft' cube with a normal map, I encountered an issue. Despite not receiving any errors or warnings while running the code, adding the normal map parameter resulted in a black object when refreshing the browser. Removi ...

Angular 13 - Encountering issue with "Cannot access properties of null (reading 'getParsed')"

Currently working on a new Angular 13 project and running into an error: TypeError: Unable to access properties of null (reading 'getParsed') at .../main.2506c840be361c93.js:1:325924 at Array.filter () at nd._getActiveElements (.../main.2506c84 ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

JavaScript Cookie to Ensure Form Submission is Limited to a Single Instance

Seeking assistance with automatically submitting a form on page load using JS cookies. Here is the code I have, but it's not functioning as expected. Any guidance would be greatly appreciated. Thank you. I'm unsure about the section in my code th ...

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

What is the best way to merge two ajax functions into a single function?

I am looking to streamline my ajax functionality by combining two separate functions. One function is used to post a name, while the other is used to upload an image. I would like to create a single function that can handle both tasks of posting a name and ...