页面加载后如何更改内容(JS)? [英] How to change content after page is loaded (JS)?

查看:83
本文介绍了页面加载后如何更改内容(JS)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在页面加载后运行javascript,如下面的示例中所示,延迟6秒.页面加载后,其余的JS丢失(很明显)...有什么想法在页面加载后如何更改内容而无需单击按钮?

I would like a javascript to run after a page is loaded , like on the example below with a delay of 6seconds. Right after the page loads the rest of JS is lost (obvious)... Got any ideea how change content after page is loaded without clicking a button?

javascript:window.location = "http://example.com"; 
setTimeout(function() {
    document.getElementById('lightbox').style.display = 'none';
}, 6000);

推荐答案

一旦您设置window.location,在浏览器加载新页面之前,原始页面将被卸载.这意味着您的脚本将在新页面开始加载之前就消失了,因此无法再修改新的HTML.

Once you set window.location the original page will be unloaded before the new page is loaded by the browser. This means your script will be gone before the new page start loading and thus can't modify the new HTML anymore.

此行为是浏览器安全模型所固有的.没有它,您可以将任何JavaScript注入您选择的任何网站,这将带来巨大的安全风险.您要的是所谓的XSS(用于跨站点脚本),通过浏览器应用所谓的SOP(用于相同原始策略)可以避免这种情况.

This behavior is inherent to the security model of the browser. Without it you could inject any JavaScript into any web site of your choosing, which would be a huge security risk. What you are asking for is so-called XSS (for cross site scripting), which is prevented by the browser applying a so-called SOP (for same-original policy).

有一些常见的方法可以安全地解决此限制:

There are some common ways to work around this limitation in a safe way:

  1. 设置代理,以同时服务您的JavaScript和原始站点.这样,您的脚本和原始站点都来自同一域,并满足浏览器的原始策略(SOP).您可以在iframe中运行原始网站,而自定义脚本将占据顶层窗口.另外,您也可以在通过代理检索脚本时将脚本注入HTML.

  1. Set up a proxy to serve both your JavaScript and the original site. This way both your script and the original site come from the same domain and satisfy the browser's same-original policy (SOP). You could run the original site in an iframe with your custom script occupying the top-level window. Alternatively you could inject your script into the HTML as it is being retrieved through your proxy.

作为浏览器加载项或用户脚本运行脚本.如果您选择这样做,用户将必须专门授予您的脚本以提升的权限在本地运行的权限.Greasemonkey在几年前就为Firefox普及了客户端脚本,但是最近它们似乎失去了动力.

Run your script as a browser add-on or user-script. If you choose to do this, the user will have to specifically grant your script the rights to run locally with elevated rights. Greasemonkey popularized client-side scripts for Firefox a few years ago, but recently they seem to have lost momentum.

询问网站所有者以包括您的脚本.我怀疑这是否适合您的情况.但是,如果这是一个有效的选择,则肯定是最简单的选择.

Ask the site owner to include your script. I doubt this is a valid option for your situation. But if it is a valid option it is definitely the simplest one.

要求用户在网站加载后运行脚本.这个可能对您也无效,但是如果有效,它将再次是一个非常简单的解决方案.

Ask the user to run your script after the site has loaded. This one is probably also not valid for you, but if valid it would once again be a very simple solution.

这篇关于页面加载后如何更改内容(JS)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆