简体   繁体   English

仅在Chrome中运行JavaScript

[英]Only run JavaScript in Chrome

So I have a little script that only seems to work correctly in Chrome. 因此,我有一个小脚本,似乎只能在Chrome中正常工作。 It's not a big problem, however the negative effects it has in other browsers is annoying, so I'd like to only run it in Chrome. 这不是一个大问题,但是它对其他浏览器的负面影响令人讨厌,因此我只想在Chrome中运行它。

This is my current working script that runs in all browsers: 这是我当前在所有浏览器中运行的脚本:

function psn() {
var myElement = document.getElementById('noti');
if(window.addEventListener) {
   // Normal browsers
   myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
   if(window.attachEvent) {
      // IE
      myElement.attachEvent('DOMSubtreeModified', contentChanged);
   }
function contentChanged() {
   // this function will run each time the content of the DIV changes
         document.getElementById('audiotag1').play();   
         var vid = document.getElementById("audiotag1");
vid.volume = 1;


}}
setTimeout(function () {psn()}, 2000);

And this is what I've tried already to make it run only in Chrome, which made the script stop working all together: 这就是我已经尝试过使其仅在Chrome中运行的方法,这使脚本停止了一起工作:

function psn() {
var myElement = document.getElementById('noti');
if(window.addEventListener) {
   // Normal browsers
   myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
   if(window.attachEvent) {
      // IE
      myElement.attachEvent('DOMSubtreeModified', contentChanged);
   }
function contentChanged() {
   // this function will run each time the content of the DIV changes
         document.getElementById('audiotag1').play();   
         var vid = document.getElementById("audiotag1");
vid.volume = 1;


}}
var isChrome = !!window.chrome;
if (isChrome) {

setTimeout(function () {psn()}, 2000);
}

Anyone know why this is just stopping everything completely? 有人知道为什么这只是完全停止了一切吗?

It is best to not have to do specific browser detection, but an easy way to see if you are using Chrome or not is the following: 最好不必进行特定的浏览器检测,但是以下一种简单的方法可以查看是否使用Chrome:

var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 ? true : false;

This will populate isChrome with either true of false . 这将使用truefalse填充isChrome。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM