变量“未被定义”在内联事件处理程序中? [英] Variable "is not defined" in inline event handler?

查看:102
本文介绍了变量“未被定义”在内联事件处理程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Chrome扩展,它将HTML注入到一个页面中,并对某些按钮具有onClick函数。这里是示例代码。



Namespace.js

  / * * 
*此内容脚本的命名空间。
* @const
* /
var namespace = {};

/ **
*要注入的HTML文本。
* /
namespace.HTML ='< input type =textsize =2placeholder =0.50'+
'onkeyup =namespace.enable(event) />';

document.body.insertAdjacentHTML('afterbegin',namespace.HTML);

namespace.enable = function(){
alert('Hello World!')
};

HTML正在被正确注入,但命名空间没有被识别。
以下是错误

  Uncaught ReferenceError:命名空间未定义
onkeyup

任何解决方法?



谢谢
<正如@zhuzhour所提到的,内容脚本运行在一个孤立的世界中,页面中的JavaScript不能访问由内容脚本定义的变量。

如果你想这样做,你需要在页面中注入JavaScript文件,正如我在其他答案中所述:https://stackoverflow.com/a/13037307/315562



换句话说,使用以下 content.js 文件注入 namespace.js



内容。 js



  injectScript(chrome.extension.getURL(/),namespace.js); 
函数injectScript(aBasePath,aScriptURL){
var scriptEl = document.createElement(script);
scriptEl.src = aBasePath + aScriptURL;
scriptEl.async = false;

(document.body || document.head || document.documentElement)
.appendChild(scriptEl);
}

您可以将其用作起点。如果您需要与Chrome扩展程序通信,则需要在注入的JavaScript文件中使用 window.postMessage 来发送消息并在内容脚本中接收消息。


I'm working on a chrome extension where it injects HTML into a page and has onClick functions to some buttons. Here is the sample code.

Namespace.js

/**
 * Namespace for this content script.
 * @const
 */
var namespace = {};

/**
 * HTML text to be injected.
 */
namespace.HTML = '<input type="text" size="2" placeholder="0.50"' +
                 'onkeyup="namespace.enable(event)" />';

document.body.insertAdjacentHTML('afterbegin', namespace.HTML);

namespace.enable = function() {
  alert('Hello World!')
};

HTML is getting injected properly but namespace is not getting recognized. Here's the error

Uncaught ReferenceError: namespace is not defined 
onkeyup

Any workarounds?

Thanks

解决方案

As @zhuzhour has mentioned, a content script is running in an isolated world the JavaScript in the page cannot access the variables defined by your content script.

If you want to do this, you need to inject the JavaScript file in the page as I have outlined in my other answer here: https://stackoverflow.com/a/13037307/315562

In other words, use the following content.js file to inject namespace.js .

content.js

injectScript( chrome.extension.getURL( "/" ), "namespace.js" );
function injectScript ( aBasePath, aScriptURL ) {
  var scriptEl = document.createElement( "script" );
  scriptEl.src = aBasePath + aScriptURL;
  scriptEl.async = false;

  (document.body || document.head || document.documentElement)
  .appendChild( scriptEl );
}

You can use this as a starting point. If you need to communicate with the Chrome extension, then you need to use window.postMessage in the injected JavaScript file to send messages and receive them in the content script.

这篇关于变量“未被定义”在内联事件处理程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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