简体   繁体   中英

Variable “is not defined” in inline event handler?

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

It works in Firefox, Chrome and IE 9 when called as:

window.onload = function() {
  document.body.insertAdjacentHTML('afterbegin', namespace.HTML);
};

Content script is running in a so-called isolated world . It can't

Use variables or functions defined by their extension's pages

Use variables or functions defined by web pages or by other content scripts

So you may need to inject your namespace as another piece of js to the HTML page as well.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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