Home Web Front-end JS Tutorial Summary of javascript cross-domain methods_javascript skills

Summary of javascript cross-domain methods_javascript skills

May 16, 2016 pm 03:35 PM

This article draws on some articles from other front-end students and makes a practical summary of my own

The following examples contain files that are http://www.a.com/a.html and http://www.a.com/c.html With http://www.b.com/b.html, all you have to do is get the data in b.html from a.html

1.JSONP

jsonp takes advantage of the fact that the script tag has no cross-domain restrictions by appending the callback function name to the url parameter of src, and then the server receives the callback function name and returns a callback function containing data

  function doSomething(data) {
    // 对data处理
  }
  var script = document.createElement("script");
  script.src = "http://www.b.com/b.html?callback=doSomething";
  document.body.appendChild(script);

  // 1.生成一个script标签,将其append在body上,向服务器发出请求
  // 2.服务器根据 callback 这个参数生成一个包含数据的函数 doSomething({"a", "1"})
  // 3.页面事先已声明doSomething函数,此时执行 doSomething(data) 这个函数,获得数据

Copy after login

2.HTML5 postMessage

Suppose an is nested in a.html , communicate with each other in these two pages

a.html

  window.onload = function() {
    window.addEventListener("message", function(e) {
      alert(e.data);
    });

    window.frames[0].postMessage("b data", "http://www.b.com/b.html");
  }
Copy after login

b.html

  window.onload = function() {
    window.addEventListener("message", function(e) {
      alert(e.data);
    });
    window.parent.postMessage("a data", "http://www.a.com/a.html");
  }
Copy after login

When you open page a in this way, a data will pop up first, and then b data will pop up

3.window.name iframe

The principle of window.name is to use the same window to share a window.name on different pages. This requires creating a proxy file c.html under a.com so that a.html can obtain c.html after the same origin. window.name

a.html

  var iframe = document.createElement("iframe");
  iframe.src = "http://www.b.com/b.html";
  document.body.appendChild(iframe); // 现在a.html里建一个引用b.html的iframe,获得b的数据

  var flag = true;
  iframe.onload = function() {
    if (flag) {
      iframe.src = "c.html"; 
// 判断是第一次载入的话,设置代理c.html使和a.html在同目录同源,这样才能在下面的else取到data
      flag = false;
    } else { // 第二次载入由于a和c同源,a可以直接获取c的window.name
      alert(iframe.contentWindow.name);

      iframe.contentWindow.close();
      document.body.removeChild(iframe);
      iframe.src = '';
      iframe = null;
    }
  }

Copy after login

b.html

window.name = "这是 b 页面的数据";
Copy after login

4.window.location.hash iframe

b.html appends the data to the url of c.html in the form of a hash value. On the c.html page, the data is obtained through location.hash and then passed to a.html (this example is the hash passed to a.html (of course it can also be uploaded to other places)

a.html

  var iframe = document.createElement("iframe");
  iframe.src = "http://www.b.com/b.html";
  document.body.appendChild(iframe); // 在a页面引用b
  function check() { // 设置个定时器不断监控hash的变化,hash一变说明数据传过来了
    var hashs = window.location.hash;
    if (hashs) {
      clearInterval(time);
      alert(hashs.substring(1));
    }
  }
  var time = setInterval(check, 30);
Copy after login

b.html

  window.onload = function() {
    var data = "this is b's data"; 
    var iframe = document.createElement("iframe");
    iframe.src = "http://www.a.com/c.html#" + data;
    document.body.appendChild(iframe); // 将数据附加在c.html的hash上
  }
Copy after login

c.html

// 获取自身的hash再传到a.html的hash里,数据传输完毕
parent.parent.location.hash = self.location.hash.substring(1); 
Copy after login

5.CORS

CORS is a cross-domain method specified in XMLHttpRequest Level 2. In browsers that support this method, the writing method of javascript is exactly the same as the writing method of ajax that does not cross domain, as long as the server needs to set Access-Control-Allow-Origin: *

6.document.domain

This method is suitable for the same main domain but different subdomains, such as http://www.a.com and http://b.a.com
If there are a.html and b.html under these two domain names,

a.html

  document.domain = "a.com";
  var iframe = document.createElement("iframe");
  iframe.src = "http://b.a.com/b.html";
  document.body.appendChild(iframe);
  iframe.onload = function() {
    console.log(iframe.contentWindow....); // 在这里操作b.html里的元素数据
  }
Copy after login

b.html

  document.domain = "a.com";
Copy after login

Note: document.domain needs to be set to itself or a higher-level parent domain, and the main domain must be the same.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles