2016-11-24 48 views
0
<html> 
<head> 
<script type="text/javascript"> 
function open_urls() { 
var url1="https://finance.yahoo.com/"; 
var newpage=window.open(url1); 
alert(newpage.document.body.innerText.split(' ').length); 
         }   
</script> 
</head> 
<body onload="javascript: open_urls()"></body> 
</html> 

上面的代码没有工作,如何访问不同的URL的DOM? 我想打开一个URL并显示该URL的字数。如何打开一个URL并使用JavaScript估计字数?

+0

可以加载与AJAX的URL的内容和解析。 – Marty

+0

“代码无效”通常在这里看不到。你应该更清楚你得到的输出和你的期望:) – geisterfurz007

+0

你想打开一个新页面,然后在该页面上显示字数吗? – sheetal

回答

1

你不能简单地打开另一个窗口和页面,并期望能够访问它。网络遵循许多安全策略来阻止这样的操作,例如Same-Origin policy。长话短说,您不能访问不属于同源的网址作为您打电话给的网页。因此,您无法在您的示例中访问雅虎财务(很可能)。

如果您是从同一来源进行调用,则可以使用类似fetch的API来获取文本并在那里进行单词计数,或者您甚至可以加载iframe并查询:myIframe.contentWindow.document.body.innerHTML

所以知道你不能从浏览器做到这一点,你可以从的NodeJS应用程序(或许也使用fetch)做到这一点:

var fetch = require('node-fetch'); 

fetch('https://finance.yahoo.com/') 
    .then(function(res) { 
     return res.text(); 
    }).then(function(body) { 
     console.log(body); 
     // perform word-count here 
    }); 

据我所知,你希望从这样做浏览器,但不幸的是,你无法为无法控制的来源这样做。

-1

你可以试试看。 在你的index.html(假设)这样写:

<html> 
<head> 
    <title>Index Page</title> 
</head> 
    <script type="text/javascript"> 
    function poponload() 
    { 
     testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600"); 

    }// here new_window.html is file you want to open or you can write any url there 
    </script> 
<body onload="javascript: poponload()"> 
    <h1>Hello this can Work</h1> 
</body> 
</html> 

而且假设你new_window.html是这样的:

<html> 
<head> 
<script> 
    function get_text(el) { 
     ret = ""; 
     var length = el.childNodes.length; 
     for(var i = 0; i < length; i++) { 
     var node = el.childNodes[i]; 
     if(node.nodeType != 8) { 
      ret += node.nodeType != 1 ? node.nodeValue : get_text(node); 
     } 
    } 
    return ret; 
} 
function run_this(){ 
    var words = get_text(document.getElementById('content')); 
    var count = words.split(' ').length; 
    alert(count); 
} 
</script> 
</head> 
<body onload='javascript: run_this()' id="content"> 
    <h1>This is the new window</h1> 

</body> 
</html> 
+0

那么你的建议是什么?托尼在雅虎工作并编辑他们的财务主页插入这个JS? – Quentin

+0

嗯,我完全误解了,@Quentin是啊谢谢你的讽刺让我意识到真正的问题在这里。 – shikhar