Passing a string with a Newline escape in it (\n) using chrome.tabs.executeScript

903 views
Skip to first unread message

Siddhesh

unread,
Feb 26, 2012, 8:33:17 AM2/26/12
to Chromium-extensions
So i need to inject a global variable into my page in my chrome
extension.

chrome.tabs.executeScript(null,{code:"var Urls='"+Urls+"';"});

The global variable gets injected as long as Urls contains a string
with no newline characters. But the moment it is populated with some
string content spanning more than a line, it refuses to work.

Reasons and workarounds plz. Fairly new to chrome and extensions.

Łukasz Łoboda

unread,
Feb 27, 2012, 2:37:04 AM2/27/12
to Siddhesh, Chromium-extensions

This  Url variable is undefined when this code is executed?


--
You received this message because you are subscribed to the Google Groups "Chromium-extensions" group.
To post to this group, send email to chromium-...@chromium.org.
To unsubscribe from this group, send email to chromium-extens...@chromium.org.
For more options, visit this group at http://groups.google.com/a/chromium.org/group/chromium-extensions/?hl=en.

Mike West

unread,
Feb 27, 2012, 3:08:24 AM2/27/12
to Siddhesh, Chromium-extensions
Hi Siddhesh,

Injecting a string with newlines would end up writing the following code:

    var Urls = "This is a string
with newlines";

That isn't valid JavaScript. You want the string that's executed to look like "This is a string\nwith newlines." Try writing something like this:

    var to_inject = urls.replace(/\n/, '\\n');
    chrome.tabs.executeScript(null, { code: 'var Urls = "' + to_inject + '";"});

That will escape the literal newline with "\n" in the string that's written out and executed.

-Mike


Reply all
Reply to author
Forward
0 new messages