JS controls static pages to pass parameters and get parameter applications

  • 2021-07-09 07:09:46
  • OfStack

This is also a problem encountered in the project:

There are a. html and b. html.

1. The a page has been opened, but the b page has not yet been opened. I hope to set up a series of parameters on the a page, such as background color, width and other parameters, and pass them to the b page, so that the b page can be applied when it is opened.

2. The a page is open, and the b page is open or not. In a page need to get b page 1 some elements or even variables, in order to apply to a page.

Note: Cross-domain issues are not involved.

After thinking for a long time, I finally came up with a solution.

First, we can use the html page anchor features to pass parameters to the b page through url

This is the a page code:


<button> Jump setting </button>
<script>
var btn = document.querySelector('button');
console.log(window);
btn.addEventListener('click', function(){
window.location = 'ci.html#bgc=#369?wd=500'
})
</script>

As you can know from the code, when you click the button to jump to the page, there are 1 series of parameters behind the jump url, which will not affect the jump address. When the b page is opened, you can get the location intercept string to get variables and variable values, and then apply them.

This is the b page code:


<div></div>
<script>
var div = document.querySelector('div');
var bl = window.location.hash.slice(1).split('?');
if(bl.length >= 1){
for(var i = 0; i < bl.length; i += 1){
switch (bl[i].split('=')[0]) {
case 'bgc':
document.body.style.background = bl[i].split('=')[1];
break;
case 'wd':
div.style.width = bl[i].split('=')[1] + 'px';
break;
default:
null;
break;
}
} 
}
</script>

Get the variable application passed by url by intercepting the string. Success!

The second question, I want to achieve the goal through iframe, which is just a blind eye.

Create an iframe dynamically on the a page, and set the src value to b page and display to none. Then get the returned document of iframe through the contentDocument attribute of iframe.

Get the required elements in the document and apply them.

Source code:


<span>11111111111</span>
<script>
var fram = document.createElement('iframe');
fram.src = 'http://www.vip.com/kongzhi/fram2.html';
fram.style.display = 'none';
document.body.appendChild(fram);
fram.onload = function(){
var doc = fram.contentDocument || fram.contentWindow.document;
var p = doc.querySelector('p');
document.body.appendChild(p);
}
</script>

Related articles: