Retrieve the CSS property value of an element on a webpage using a URL that is from the same origin

Seeking advice on how to obtain the background color of an element located on a different webpage within the same domain. My current approach involves loading the external page into an iframe, but I believe there must be a more efficient method that someone can guide me towards.

Current Approach

To start, I embed the external page within an iframe:

var $page = $('<iframe/>').attr('src', 'http://mydomain.com/page');

I then add this iframe to my existing page:

$('#iframe-placeholder').append($page);

Finally, I retrieve the CSS property:

$('iframe').load(function(){
  var backgroundColor = $(this).contents().find('#my-element').css('backgroundColor');
});

Limitations of Current Method

  1. It's slow
  2. It's asynchronous
  3. It's not entirely effective as it always returns transparent.

Query

Is there a synchronous way to access the CSS property of the external page? Ideally, I would prefer to avoid loading the entire page into an iframe as it seems excessive. Any insights or recommendations would be greatly appreciated...

Answer №1

Have you attempted to asynchronously load the page content and proceed from there?

var bgColor;
$.ajax({
    type: 'GET',
    url: 'http://mydomain.com/page',
    dataType: 'html',
    success: function(pageData) {
        var page = $(pageData);
        bgColor = page.find('#my-element').css('backgroundColor');
    }
});

Please keep in mind that this code has not been tested.

Answer №2

Yes, I understand the allure of using iframes to bypass the same origin policy, but I want to bring your attention to another solution: CORS

Imagine a scenario where the website alice.com holds data that bob.com needs access to. By enabling CORS requests, alice.com can include specific response headers that allow bob.com to retrieve the data.

Step-by-Step Example :

// Initialize the XHR object.
function setupCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Utility function to extract the title tag from the response.
function fetchTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Execute the CORS request.
function initiateCorsRequest() {
  // All HTML5 Rocks properties support CORS.
  var url = 'http://updates.html5rocks.com';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Define response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response received from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Oops, an error occurred while making the request.');
  };

  xhr.send();
}

Test out the code and monitor the network requests in your browser's developer tools to observe the actual HTTP request being sent.

For further insight into how this technique operates, feel free to explore the provided website.

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

Tips For Making Your Bootstrap 4 Page Fit Perfectly on Mobile Screens

Currently in the process of developing . The frontpage has been created and tested using Chrome's dev console's device toolbar. Ensured that the correct viewport is set and utilized Bootstrap's column system for stacking elements. However, ...

Ways to retrieve a webpage component that has multiple values within its class attribute

My dilemma lies in this HTML snippet: https://i.sstatic.net/E7zj0.png Within the code, there are two instances of <div class="sc-fjhmcy dbJOiq flight-information"></div>. I am trying to target these elements using their class attribu ...

Unable to process response from the $.ajax API POST request

Having an issue calling a REST API from my login page when clicking on a button. I am using $.ajax to make the POST request, and the backend shows a 200 code response. However, in the browser network tab, it displays as failed. The response from the API is ...

Position the dropdown items of the navbar side by side

I am currently struggling to align my Bootstrap 4 dropdown items side by side as shown below: https://i.sstatic.net/i3pP0.png The desired layout involves having Item 1 and Item 2 as dropdown options when hovering over the first Test item. I attempted to ...

Having difficulty retrieving data from JSON file using Backbone framework

When I click on the div, I am attempting to retrieve JSON data but am unable to view the output. I am utilizing Backbone Collection to fetch JSON data. I have tried displaying the JSON data in the console as well as within another div. The contents of the ...

Inject AngularJS variable bindings into the view alongside HTML code

Is it possible to insert HTML markup into an Angular variable? app.js function myController($scope){ $scope.myItem = '<p>' + Example + '</p>'; } index.html <div ng-controller="myController">{{myItem}}</div&g ...

The Codepen demo for SemanticUI is not functioning properly

Click here to view the example on CodePen $('.ui.sidebar').sidebar({ context: $('.bottom.segment') }) .sidebar('attach events', '.menu .item'); I am currently trying to replicate this specific functiona ...

Expand the contents inside a div without affecting the actual div

Is there a way to zoom out the contents of a div similar to how a browser zooms out a page? I'm working on an application that loads a page into a div. However, I want to load the content without scroll bars. This would require zooming out the conten ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

The program is functioning properly, however it is only showing me the last 5 entries when using Ajax

My code is functioning correctly, but it's only displaying the last 5 records out of over 100. Strangely, without using Ajax, all records are displayed. I'm working on developing MLM Software with 15 levels where records are displayed based on re ...

Is there a way to ensure a div expands according to screen resolution rather than content size?

I'm currently working on a website where the right-side sidebar should extend to the bottom of the page across various screen resolutions using the height:100%; property. However, I'm facing an issue where it only extends to the content within it ...

Guide to getting Material-UI Dialog up and running smoothly in your React application

I'm currently working on a project using material-UI, and I'm having trouble with the Dialog component not working properly. Despite trying various solutions, I haven't been able to get it to function correctly in my React application with m ...

The display of basic text may not appear correctly within an HTML input tag sourced from an .resx file

Within my resx file, there is an entry: AccountRegisterSubmit = Create a new account Within my View: @{ ViewBag.Submit = @Resources.AccountRegisterSubmit; } <div> <input type="submit" <a href="/cdn-cgi/l/email-protection" cl ...

Excessive spacing on the left-hand side of the navigation bar

I am noticing a small gap between my navigation links, approximately 2px wide, and I am struggling to remove it. Is there any CSS code that can help with this? Upon hovering over the "Downloads" link, you can see the space on the left side. Check out the ...

Display a toast in the bottom-right corner of the screen upon scrolling down using Bootstrap 5

When using classes bottom-0 end-0, I have noticed that the results are not as expected. It seems like there might be something fundamental about css and positioning that I am missing. Below is a concise example of the code: <!DOCTYPE html> < ...

When an image is clicked, I am interested in loading HTML content

I am trying to implement a feature where a local HTML page can be loaded within a div to replace an existing one without the entire page having to reload. An example of what I want to achieve can be seen at . When you click on the game image, the player i ...

Issues with html2canvas crashing have been reported specifically on iOS devices

I recently developed a system for a client that enables users to select or upload an image of a car, input a number plate, adjust the positioning of the plate by moving, resizing, rotating, and skewing it as needed, and then download the modified image: E ...

"Exploring the implementation of mute event in Audio HTML5 using JavaScript within an MVC

I am searching for an event that triggers when the mute button is pressed. The volumechange event only works when the volume is adjusted. <audio id="volumeController" onvolumechange="changeVolume()"controls> <source src="~/Sounds/be ...

Problem saving videos when using the right-click function

Hello, I am currently working on retrieving videos from a database, but I have encountered an issue with the video saving option. When a user right-clicks on the video, they are able to save it in their system's storage. What I would like to achieve ...

Replicating DIV element with input field

Once again, I find myself stuck in my attempt to duplicate a DIV and its form elements using jQuery. Button: <div class="addNew" id="addSkill">Add Skill <i class="icon-plus"></i></div> This is the Div and contents that I want to ...